問題 C: 還原二叉樹
時間限制: 1 Sec
內存限制: 128 MB
提交: 322
解決: 153
題目描述
給一棵二叉樹的層序遍歷序列和中序遍歷序列,求這棵二叉樹的先序遍歷序列和后序遍歷序列。
輸入
每個輸入文件中一組數據。
第一行一個正整數N(1<=N<=30),代表二叉樹的結點個數(結點編號為1~N)。接下來兩行,每行N個正整數,分別代表二叉樹的層序遍歷序列和中序遍歷序列。數據保證序列中1~N的每個數出現且只出現一次。
輸出
輸出兩行,每行N個正整數,分別代表二叉樹的先序遍歷序列和后序遍歷序列。每行末尾不輸出額外的空格。
樣例輸入
7
3 5 4 2 6 7 1
2 5 3 6 4 7 1
樣例輸出
3 5 2 4 6 7 1
2 5 6 1 7 4 3
解題思想:
習慣通過靜態的方式來處理樹的問題了。整個過程相當於模擬二叉樹的層次遍歷將二叉樹還原出來,最后對其進行遍歷。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #define MAXN 100 5 using namespace std; 6 typedef struct Node{ 7 int v,L,R; 8 Node(){v=L=R=-1;} 9 }Node; 10 Node node[MAXN]; 11 int lt[MAXN],it[MAXN],flag[MAXN],a; 12 void pro(int x){ 13 if(a==0){ 14 printf("%d",node[x].v); 15 a=1; 16 }else{ 17 printf(" %d",node[x].v); 18 } 19 if(node[x].L!=-1){ 20 pro(node[x].L); 21 } 22 if(node[x].R!=-1){ 23 pro(node[x].R); 24 } 25 } 26 void post(int x){ 27 if(node[x].L!=-1){ 28 post(node[x].L); 29 } 30 if(node[x].R!=-1){ 31 post(node[x].R); 32 } 33 if(a==0){ 34 printf("%d",node[x].v); 35 a=1; 36 }else{ 37 printf(" %d",node[x].v); 38 } 39 } 40 int main() 41 { 42 int n; 43 scanf("%d",&n); 44 for(int i=0;i<n;i++) 45 scanf("%d",<[i]); 46 for(int i=0;i<n;i++) 47 scanf("%d",&it[i]); 48 49 memset(flag,0,sizeof(flag)); 50 int index1,index2; 51 index1=index2=0; 52 for(int i=0;index1<n;){ 53 if(node[index1].v==-1){ 54 node[index1].v=lt[i++]; 55 } 56 int c=0; 57 while(node[index1].v!=it[c]) 58 c++; 59 flag[c]=1; 60 if(c>0&&flag[c-1]!=1){ 61 node[index1].L=i; 62 node[i].v=lt[i++]; 63 c=0; 64 while(node[index1].v!=it[c]) 65 c++; 66 flag[c]=1; 67 } 68 if(c<n-1&&flag[c+1]!=1){ 69 node[index1].R=i; 70 node[i].v=lt[i++]; 71 c=0; 72 while(node[index1].v!=it[c]) 73 c++; 74 flag[c]=1; 75 } 76 index1++; 77 } 78 a=0; 79 pro(0); 80 printf("\n"); 81 a=0; 82 post(0); 83 printf("\n"); 84 //for(int i=0;i<n;i++) 85 // printf("%d %d %d\n",node[i].v,node[i].L,node[i].R); 86 return 0; 87 }