1 #include<stdio.h>
2 #include<stdlib.h>
3 #define ok 1
4 #define error 0
5 typedef int status;
6 typedef char TElemType;
7 typedef struct BiTNode
8 {
9 TElemType data;
10 struct BiTNode *lchild,*rchild;
11 }BiTNode,*BiTree;
12
13 void InitBiTree(BiTree &T)
14 {
15 T=NULL;
16 }
17 void DestroyBiTree(BiTree &T)
18 {
19 if(T)
20 {
21 DestroyBiTree(T->lchild);
22 DestroyBiTree(T->rchild);
23 free(T);
24 T=NULL;
25 }
26 }
27 status CreateBiTree(BiTree &T)
28 {
29 char ch;
30 ch=getchar();
31 if(ch==' ') T=NULL;
32 else
33 {
34 if(!(T=(BiTNode *)malloc(sizeof(BiTNode)))) exit(error);
35 T->data=ch;
36 CreateBiTree(T->lchild);
37 CreateBiTree(T->rchild);
38 }
39 return ok;
40 }
41 void PreOrderTraverse(BiTree T)
42 {
43 if(T)
44 {
45 printf("%c",T->data);
46 PreOrderTraverse(T->lchild);
47 PreOrderTraverse(T->rchild);
48 }
49 }
50 void InOrderTraverse(BiTree T)
51 {
52 if(T)
53 {
54 InOrderTraverse(T->lchild);
55 printf("%c",T->data);
56 InOrderTraverse(T->rchild);
57 }
58 }
59 void PostOrderTraverse(BiTree T)
60 {
61 if(T)
62 {
63 PostOrderTraverse(T->lchild);
64 PostOrderTraverse(T->rchild);
65 printf("%c",T->data);
66 }
67 }
68 status CountLeaf(BiTree T)
69 {
70 int count=0;
71 if(T)
72 {
73 if((!T->lchild)&&(!T->rchild))
74 count++;
75 count+=CountLeaf( T->lchild);
76 count+=CountLeaf( T->rchild);
77 }
78 return count;
79 }
80 status Depth(BiTree T)
81 {
82 int depthval=0;
83 int depthLeft,depthRight;
84 if(!T) depthval = 0;
85 else
86 {
87 depthLeft = Depth( T->lchild );
88 depthRight= Depth( T->rchild );
89 depthval = 1 + (depthLeft > depthRight ? depthLeft : depthRight);
90 }
91 return depthval;
92 }
93 int main()
94 {
95 BiTree T;
96 InitBiTree(T);
97 int count,depthval;
98 printf("请输入你要建立的二叉树\n");
99 CreateBiTree(T);
100 printf("先序遍历的结果是:\n");
101 PreOrderTraverse(T);
102 putchar('\n');
103 printf("中序遍历的结果是:\n");
104 InOrderTraverse(T);
105 putchar('\n');
106 printf("后序遍历的结果是:\n");
107 PostOrderTraverse(T);
108 putchar('\n');
109 count=CountLeaf(T);
110 printf("统计叶子的个数为:%d\n",count);
111 depthval=Depth(T);
112 printf("统计树的深度为:%d\n",depthval);
113 system("pause");
114 return 0;
115 }