添加链接描述

#include<bits/stdc++.h>
using namespace std;
const int N=50;
int in[N],pre[N];
typedef struct node {
	node *l, *r;
	int data;
}bitnode;
node *build(int inl,int inr,int prel,int prer){
	if(inl>inr)return NULL;
	bitnode *root;
	root=new node ();
	root->data=pre[prel];
	int p=pre[prel],k=inl;
	while(in[k]!=p)k++;
	int len=k-inl;
	root->l=build(inl,inl+len-1,prel+1,prel+len);
	root->r=build(k+1,inr,prel+len+1,prer);
	return root;
}
vector<int>v[N];
typedef pair<node*,int > pii;
void bfs(node *root){
	queue<pii>q;
	q.push({root,0});
	while(q.size()){
		auto p=q.front();q.pop();
		v[p.second].push_back(p.first->data);
		if(p.first->l!=NULL)q.push({p.first->l,p.second+1});
		if(p.first->r!=NULL)q.push({p.first->r,p.second+1});
	}
}
int main(){
    std::ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)cin>>in[i];
	for(int i=1;i<=n;i++)cin>>pre[i];
	bitnode *root=build(1,n,1,n);
	bfs(root);
	int ok=0;
	for(auto it:v){
		if(it.size()){
			for(int i=it.size()-1;i>=0;i--){
				if(ok)cout<<" ";
				ok=1;
				cout<<it[i];
			}
		}
	}
    return 0;
}