统计利用先序遍历创建的二叉树的宽度
输入为接受键盘输入的由大写英文字符和"#"字符构成的一个字符串(用于创建对应的二叉树)。
输出该用例对应的二叉树的宽度。
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 }
原文:https://www.cnblogs.com/Iwpml-595/p/10691527.html