swust oj 972

统计利用先序遍历创建的二叉树的宽度

1000(ms)
10000(kb)
2938 / 6810
利用先序递归遍历算法创建二叉树并计算该二叉树的宽度。先序递归遍历建立二叉树的方法为:按照先序递归遍历的思想将对二叉树结点的抽象访问具体化为根据接收的数据决定是否产生该结点从而实现创建该二叉树的二叉链表存储结构。约定二叉树结点数据为单个大写英文字符。当接收的数据是字符"#"时表示该结点不需要创建,否则创建该结点。最后再统计创建完成的二叉树的宽度(是指二叉树每层节点数的最大值)。需要注意输入数据序列中"#"字符和非"#"字符的序列及个数关系,这会最终决定创建的二叉树的形态。

输入

输入为接受键盘输入的由大写英文字符和"#"字符构成的一个字符串(用于创建对应的二叉树)。

输出

输出该用例对应的二叉树的宽度。

样例输入

A##
ABC####
AB##C##
ABCD###EF##G###
A##B##

样例输出

1
1
2
3
1 
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<cstdio>
 6 typedef int Datetype;
 7 using namespace std;
 8 int x;
 9 typedef struct link{
10     Datetype date;
11     struct link *lchild;
12     struct link *rchild;
13 }tree;
14 
15 void creattree(tree *&L)
16 {
17     char c;
18     cin>>c;
19     if(c=='#')
20         L=NULL;
21     else
22     {
23         L = (tree *)malloc(sizeof(tree)) ;
24         L->date=c;
25         creattree(L->lchild);
26         creattree(L->rchild);
27     }
28 }
29 
30 void destroytree(tree *&L)
31 {
32     if(L!=NULL)
33     {
34         destroytree(L->lchild);
35         destroytree(L->rchild);
36         free(L);
37     }
38 }
39 
40 int deep(tree *L)
41 {
42     int ldep,rdep,max;
43     if(L!=NULL)
44     {
45         ldep=deep(L->lchild);
46         rdep=deep(L->rchild);
47         max=ldep>rdep?ldep+1:rdep+1;
48         return max;
49     }
50     else
51         return 0;
52 }
53 
54 void wigth(tree *L,int ptr[],int i)
55 {
56     if(i<x&&L!=NULL)
57     {
58         ptr[i]++;
59         wigth(L->lchild,ptr,i+1);
60         wigth(L->rchild,ptr,i+1);
61     }
62 }
63 
64 int main()
65 {
66     tree *L = NULL;
67     int ptr[100]={0},max=0;
68     creattree(L);
69     x=deep(L);
70     wigth(L,ptr,0);
71     for(int i=0;i<x;i++)
72     {
73         if(ptr[i]>max)
74         max=ptr[i];
75     }
76     cout<<max;
77     destroytree(L);
78     return 0;
79 }

猜你喜欢

转载自www.cnblogs.com/Iwpml-595/p/10691527.html