给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤ 30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7 2 3 1 5 7 6 4 1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
1 #include <bits/stdc++.h> 2 const int INF=0x3f3f3f3f; 3 typedef long long LL; 4 const double eps =1e-8; 5 const int mod=1e9+7; 6 const int maxn=1e5+10; 7 using namespace std; 8 9 int n; 10 int a[50]; //后序 11 int b[50]; //中序 12 vector<int> vt; //存层序 13 int T[50][2]; 14 15 void solve(int L1,int R1,int L2,int R2,int pre,int f)//f表示左还是右 16 { 17 int rt=a[R1]; 18 if(pre!=-1) 19 T[pre][f]=rt; 20 int pos; 21 for(int i=L2;i<=R2;i++) 22 { 23 if(b[i]==rt) 24 { 25 pos=i; 26 break; 27 } 28 } 29 int la=pos-L2; 30 int lb=R2-pos; 31 if(la) solve(L1,L1+la-1,L2,pos-1,rt,0); 32 if(lb) solve(R1-lb,R1-1,pos+1,R2,rt,1); 33 } 34 35 void BFS(int st)//求出层序遍历 36 { 37 queue<int> qe; 38 qe.push(st); 39 while(!qe.empty()) 40 { 41 int u=qe.front(); qe.pop(); 42 vt.push_back(u); 43 for(int i=0;i<=1;i++) 44 { 45 int v=T[u][i]; 46 if(v) qe.push(v); 47 } 48 } 49 } 50 51 int main() 52 { 53 #ifdef DEBUG 54 freopen("sample.txt","r",stdin); 55 #endif 56 57 scanf("%d",&n); 58 for(int i=1;i<=n;i++) 59 scanf("%d",&a[i]); 60 for(int i=1;i<=n;i++) 61 scanf("%d",&b[i]); 62 solve(1,n,1,n,-1, -1); 63 BFS(a[n]); 64 for(int i=0;i<n;i++) 65 printf(i==n-1?"%d ":"%d ",vt[i]); 66 67 return 0; 68 }
-