#include<bits/stdc++.h>
using namespace std;
const int N = 31;
int n;
int in[N],post[N],h[N];
struct node{
int data;
node *lchild = NULL,*rchild = NULL;
};
node* build(int la,int ra,int lb,int rb)
{
if(la>ra||lb>rb) return NULL;
node *ne = new node;
ne -> data = post[ra];
int cnt = rb - h[post[ra]];
ne -> lchild = build(la,ra - cnt - 1,lb,h[post[ra]] - 1);
ne -> rchild = build(ra-cnt,ra-1,h[post[ra]] + 1,rb);
return ne;
}
void level(node *v)
{
queue<node*> q;
q.push(v);
int cnt = 1;
while(q.size()){
auto i = q.front();
q.pop();
if(cnt == 1) cout<<i -> data;
else cout<<' '<<i->data;
if(i -> lchild)q.push(i -> lchild);
if(i -> rchild)q.push(i -> rchild);
cnt++;
}
}
int main()
{
cin>>n;
for(int i=0;i<n;i++) cin>>post[i];
for(int i=0;i<n;i++) cin>>in[i],h[in[i]] = i;
node *root = new node;
root = build(0,n-1,0,n-1);
level(root);
return 0;
}
L2-006 树的遍历(各种遍历的相互转换)
于 2023-08-11 20:04:37 首次发布