1 #include <bits/stdc++.h> 2 using namespace std; 3 const int N=100; 4 queue <int> q; 5 int a[N]; 6 int b[N]; 7 int n; 8 struct T { 9 int key; 10 int ls; 11 int rs; 12 }; 13 int cnt; 14 T t[N]; 15 int dfs (int l1,int h1,int l2,int h2) { 16 if (l1>h1) return 0; 17 int rt=++cnt;// 保留rt 而不是直接使用cnt 18 t[rt].key=a[h1]; 19 int p; 20 for (int i=l2;i<=h2;i++) 21 if (b[i]==a[h1]) { 22 p=i; 23 break; 24 } 25 t[rt].ls=dfs (l1,l1+p-l2-1,l2,p-1);// 保证区间相同 26 t[rt].rs=dfs (l1+p-l2,h1-1,p+1,h2); 27 return rt; 28 } 29 int main () 30 { 31 cin>>n; 32 for (int i=1;i<=n;i++) cin>>a[i];// 后序 33 for (int i=1;i<=n;i++) cin>>b[i];// 中序 34 int root =dfs (1,n,1,n); 35 bool flag=1; 36 q.push(root); 37 while (!q.empty()) { 38 int k=q.front(); q.pop(); 39 if (flag) { cout<<t[k].key; flag=0; } 40 else cout<<" "<<t[k].key; 41 if (t[k].ls) q.push(t[k].ls); 42 if (t[k].rs) q.push(t[k].rs); 43 } 44 cout<<endl; 45 return 0; 46 }