1 #include<stdio.h>
2 #include<stdlib.h>
3 typedef struct BiTNode
4 {
5 char data;
6 struct BiTNode *lchild,*rchild;
7 }BiTNode,*BiTree;
8 void main()
9 {
10 //采用先序遍历构造二叉树
11 void CreateBiTree(BiTree &t);
12 //中序遍历二叉树
13 void InOrder(BiTree t);
14 //统计二叉树的宽度
15 int BiTreeWidth(BiTree t);
16 BiTree t;
17 CreateBiTree(t);
18 printf("中序遍历序列:\n");
19 InOrder(t);
20 printf("\n");
21 printf("统计树的宽度\n");
22 int width=BiTreeWidth(t);
23 printf("%d\n",width);
24
25 }
26 //采用先序遍历构造二叉树
27 void CreateBiTree(BiTree &t)
28 {
29 char ch;
30 scanf("%c",&ch); //读入一个字符
31 if(ch==' ') t=NULL;
32 else
33 {
34 t=(BiTNode *)malloc(sizeof(BiTNode));
35 t->data=ch;
36 CreateBiTree(t->lchild);
37 CreateBiTree(t->rchild);
38 }
39 }
40 //中序遍历二叉树
41 void InOrder(BiTree t)
42 {
43 if(t)
44 {
45 InOrder(t->lchild);
46 printf("%c ",t->data);
47 InOrder(t->rchild);
48 }
49 }
50 //统计二叉树的宽度
51 int BiTreeWidth(BiTree t)
52 {
53 BiTree a[100];
54 BiTree p;
55 int count=0;
56 int rear=-1,front=-1;
57 int last,max=0;
58 if(t)
59 {
60 a[++rear]=t;
61 max=1;
62 last=0;
63 while(front!=rear)
64 {
65 p=a[++front];
66 if(p->lchild!=NULL)
67 {
68 a[++rear]=p->lchild;
69 ++count;
70 }
71 if(p->rchild!=NULL)
72 {
73 a[++rear]=p->rchild;
74 ++count;
75 }
76 if(front==last)
77 {
78 if(max<count)
79 max=count;
80 count=0;
81 last=rear;
82 }
83 }
84 }
85 return max;
86 }