先序建立二叉树,树的节点用一个结构体来表示,结构体包含三个元素,节点的值,指向节点左右子数的结构体指针,如下所示。
4 typedef struct Btree{5 int value;
6 struct Btree *lchild;
7 struct Btree *rchild;
8 }*Btree,BtreeNode;
有了树的节点,我们就可以利用递归建立一个二叉树,函数体如下。
9 Btree ConstructionBtree(){10 int nvalue;
11 Btree root;
12 scanf("%d",&nvalue);
13 if(nvalue == 0)
14 root = NULL;
15 else {
16 root = (Btree)malloc(sizeof(BtreeNode));
17 root->value = nvalue;
18 root->lchild = ConstructionBtree();
19 root->rchild = ConstructionBtree();
20 }
21 return root;
22 }
这里循环输入根节点的值,如果值为0则表示该子树为空,建立过后先序打印整个树,程序如下
23 void PreOrderPrintf(Btree T){24 if(T == NULL)
25 return ;
26 printf("%d ",T->value);
27 PreOrderPrintf(T->lchild);
28 PreOrderPrintf(T->rchild);
29 }
下面是main函数
30 int main(){31 Btree T;
32 printf("Please input the value of Btree,0 is the end:\n");
33 T = ConstructionBtree();
34 printf("The PreOrder of Btree is:\n");
35 PreOrderPrintf(T);
36 printf("\n");
37 return 0;
38 }