二叉树的完整代码实现

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<malloc.h>
 4     
 5 typedef struct Node//结构体  
 6 {
 7     char data;
 8     struct Node *LChild;
 9     struct Node *RChild;
10 } BinNode,*BinTree;
11 
12 BinTree CreateTree(BinTree T)
13 {
14     char ch;
15     scanf("%c",&ch);
16     if(ch=='#')
17         return NULL;
18     else
19     {
20         T=(BinTree)malloc(sizeof(BinNode));
21         T->data=ch;
22         T->LChild=CreateTree(T->LChild);/*创建左子树*/
23         T->RChild=CreateTree(T->RChild);/*创建右子树*/
24         return T;
25     }
26 }
27 
28 void PreOrder(BinTree root)//先序遍历 
29 {
30     if (root != NULL)
31     {
32         printf("%c", root->data);
33         PreOrder(root->LChild);
34         PreOrder(root->RChild);
35     }
36 }
37 
38 void InOrder(BinTree root)//中序遍历 
39 {
40     if (root != NULL)
41     {
42         InOrder(root->LChild);
43         printf("%c", root->data);
44         InOrder(root->RChild);
45     }
46 }
47 
48 void PostOrder(BinTree root)//后序遍历 
49 {
50     if (root != NULL)
51     {
52         PostOrder(root->LChild);
53         PostOrder(root->RChild);
54         printf("%c", root->data);
55     }
56 }
57 /*求二叉树结点总数*/
58 int Count(BinTree T)
59 {
60     if(T==NULL)
61         return 0;                   /*空二叉树结点数为0*/
62     else                            /*左右子树结点总数加1*/
63         return Count(T->LChild)+Count(T->RChild)+1;
64 }
65 //叶子数 
66 int LeafCount(BinTree T){
67     if(T == NULL){
68         return 0;
69     }
70     else if ((T->LChild==NULL) && (T->RChild==NULL)){
71         return 1;
72     }
73     else{
74         return LeafCount(T->LChild)+LeafCount(T->RChild);
75     }
76 }
77 int main()
78 {
79 
80     BinTree bt;
81     printf("一、请按先序的方式输入二叉树的结点元素(注:输入#表示节点为空)如:ABC##DE#G##F###
");
82     bt=CreateTree(bt);
83     printf("二、前序遍历二叉树:
");
84     PreOrder(bt);
85     printf("
");
86     printf("三、中序遍历二叉树:
");
87     InOrder(bt);
88     printf("
");
89     printf("四、后序遍历二叉树:
");
90     PostOrder(bt);
91     printf("
");
92     printf("五、二叉树结点数: %d
",Count(bt));
93     printf("六、叶子节点的个数:%d 
",LeafCount(bt));
94     system("pause");
95 }
原文地址:https://www.cnblogs.com/wy0526/p/12990884.html