#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=50;
int pre_order[maxn],in_order[maxn];
int lch[maxn],rch[maxn],s[maxn];
int n;
queue<int> q;
int build_tree(int l1,int r1,int l2,int r2){
if(l1>r1) return 0;
int pos=l2,root=pre_order[l1];
while(root!=in_order[pos]) pos++;
int cnt=pos-l2;
lch[root]=build_tree(l1+1,l1+cnt,l2,pos-1);
rch[root]=build_tree(l1+cnt+1,r1,pos+1,r2);
return root;
}
void BFS(int root){
q.push(root);
int i=0;
while(!q.empty()){
int node=q.front();
q.pop();
s[i++]=node;
if(rch[node]) q.push(rch[node]);
if(lch[node]) q.push(lch[node]);
}
for(int ii=0;ii<i;ii++){
if(ii) cout<<" ";
cout<<s[ii];
}
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&in_order[i]);
for(int i=0;i<n;i++)
scanf("%d",&pre_order[i]);
int root=build_tree(0,n-1,0,n-1);
BFS(root);
return 0;
}
L2-011 玩转二叉树
最新推荐文章于 2024-04-18 14:56:15 发布