#include<stdio.h>
#include<stdlib.h>
/**
*简单地创建一棵树
*三个函数:1.先序遍历创建树,-1作为空指针标志
* 2.输出先序遍历序列
* 3.计算所有结点data域的和
*在main函数中声明指向根结点的指针变量
*并输出和sum
*/
typedef struct tree
{
int data;
struct tree *lchild, *rchild;
}Tree; //结构体声明
int main()
{
void createTree(Tree *t);
int calSum(Tree *t);
void dispTree(Tree *t); //函数声明
Tree *t;
int sum;
createTree(t);
sum = calSum(t);
dispTree(t);
printf("%d\n", sum); //创建、计算sum、输出先序序列和输出sum
return 0;
}
void createTree(Tree *t)
{
int x;
scanf("%d", &x);
if(x == -1)
t = NULL;
t = (Tree *)malloc(sizeof(Tree));
t->data = x;
createTree(t->lchild);
createTree(t->rchild);
}
int calSum(Tree *t)
{
if(!t) return 0;
return calSum(t->lchild) + calSum(t->rchild) + t->data;
}
void dispTree(Tree *t)
{
if(t)
{
printf("%d ", t->data);
dispTree(t->lchild);
dispTree(t->rchild);
}
}