题目链接:https://www.patest.cn/contests/gplt/L2-006
代码:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
using namespace std;
const int maxn =30+5;
int a[maxn],b[maxn],lch[maxn],rch[maxn],n;
int build(int L1,int R1,int L2,int R2)//建树
{
if(L1>R1)
return 0;
int root=a[R2];
int p=L1;
while(b[p]!=root)
p++;
int cnt=p-L1;
lch[root]=build(L1,p-1,L2,L2+cnt-1);
rch[root]=build(p+1,R1,L2+cnt,R2-1);
return root;
}
vector <int>ans;
void dfs(int s)
{
queue<int> q;
ans.clear();
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
ans.push_back(u);
if(lch[u]!=0)
q.push(lch[u]);
if(rch[u]!=0)
q.push(rch[u]);
}
return;
}
int main()
{
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%d",&a[i]);//后序遍历
for(int i=0; i<n; i++)
scanf("%d",&b[i]);//后序遍历
build(0,n-1,0,n-1);
dfs(a[n-1]);
vector<int>::iterator it;
for( it = ans.begin(); it < ans.end()-1; it++ )
printf("%d ",*it);
printf("%d\n",ans.back());
}