swust oj 972
阿新 • • 發佈:2019-04-11
pan 最終 styles 先序 eat style pac 序列 sample
統計利用先序遍歷創建的二叉樹的寬度
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 namespacestd; 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 }
swust oj 972