数据结构实验之二叉树的建立与遍历

 1 # include <stdio.h>
 2 # include <malloc.h>
 3 # include <string.h>
 4 struct tree
 5 {
 6  char data;
 7  struct tree *l;
 8  struct tree *r;
 9 };
10 //构造二叉树;
11 struct tree *creatbt(struct tree *T)
12 {
13   char ch = getchar(); 
14   if(ch == ',') 
15    T=NULL;
16   else
17   {
18    T=(struct tree *)malloc(sizeof(struct tree));
19    T->data=ch;
20    T->l=creatbt(T->l);//保留住在函数里面改变的东西。
21 
22     //如果T在main函数里面申请空间,可以直接进行改变;
23    T->r=creatbt(T->r);
24   }
25   return T;
26 }
27 //中序遍历;
28 void inorder(struct tree *T)
29 {
30  if(T != NULL)
31  {
32   inorder(T->l);
33   printf("%c",T->data);
34   inorder(T->r);
35  }
36 }
37 //后序遍历;
38 void postorder(struct tree *T)
39 {
40  if(T)
41  {
42   postorder(T->l);
43   postorder(T->r);
44   printf("%c",T->data);
45 
46  }
47 }
48 //树叶计数;
49 int countleaf(struct tree *T,int count)
50 {
51  if(T)
52  {
53   if((!T->l) && (!T->r))
54    count++;
55   count=countleaf(T->l,count);
56   count=countleaf(T->r,count);
57  }
58  return count;
59 }
60 //二叉树深度;T指向二叉树的根,level 为 T 所指结点所在层次, 其初值为1,depth当前求得的最大层次,初值为0
61 int depth(struct tree *T,int level,int h)
62 {
63  if(T)
64  {
65   if(level>h)
66    h=level;//记录结案数调用当中出现的最大的。
67   h=depth(T->l,level+1,h);
68   h=depth(T->r,level+1,h);
69  }
70  return h;
71 }
72 
73 
74 int main()
75 {
76  int count=0,h=0,level=1;
77  struct tree *T; 
78  T=creatbt(T);
79  inorder(T);
80  printf("\n");
81  postorder(T);
82  printf("\n");
83  count=countleaf(T,count);
84  h=depth(T,level,h);
85  printf("%d\n%d\n",count,h);
86  return 0;
87 }
View Code

 

posted on 2013-08-03 11:38  随风浪子的博客  阅读(121)  评论(0编辑  收藏  举报

导航