层序:顶层往下,一层一层,从左到有;
前序遍历:
1.访问根节点
2.前序遍历左子树
3.前序遍历右子树
中序遍历:
1.中序遍历左子树
2.访问根节点
3.中序遍历右子树
后序遍历:
1.后序遍历左子树
2.后序遍历右子树
3.访问根节点
#include<algorithm>
#include<set>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<queue>
#include<cmath>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<ctime>
#include<map>
#include<stack>
#include<string>
using namespace std;
#define sfi(i) scanf("%d",&i)
#define pri(i) printf("%d\n",i)
#define sff(i) scanf("%lf",&i)
#define ll long long
#define mem(x,y) memset(x,y,sizeof(x))
#define INF 0x3f3f3f3f
#define eps 1e-6
#define PI acos(-1)
#define lowbit(x) ((x)&(-x))
#define zero(x) (((x)>0?(x):-(x))<eps)
#define fl() printf("flag\n")
ll gcd(ll a,ll b){while(b^=a^=b^=a%=b);return a;}
const int maxn=2e5+9;
const int mod=998244353;
template <class T>
inline void sc(T &ret)
{
char c;
ret = 0;
while ((c = getchar()) < '0' || c > '9');
while (c >= '0' && c <= '9')
{
ret = ret * 10 + (c - '0'), c = getchar();
}
}
ll power(ll x,ll n)
{
ll ans=1;
while(n)
{
if(n&1) ans=ans*x%mod;
x=x*x%mod;
n>>=1;
}
return ans;
}
struct node
{
int l,r;
}tree[maxn];
int h[maxn],z[maxn];
int build(int lz,int rz,int lh,int rh)
{
if(lz>rz) return 0;
int rt=h[rh];//后序中子树最后一个是根
int p=lz;
while(z[p]!=rt) p++;//在中序中找到根,左边就是左子树的节点,右边同理
//tree[rt].l=build(lz,p-1,lh,p-1);p-1不行的,因为左区间不对齐,要用长度
//tree[rt].r=build(p+1,rz,p,rh-1);
int len=p-lz;
tree[rt].l=build(lz,p-1,lh,lh+len-1);
tree[rt].r=build(p+1,rz,lh+len,rh-1);
return rt;
}
void bfs(int rt)
{
vector<int>ans;
queue<int>q;
q.push(rt);
while(!q.empty())
{
int s=q.front();
q.pop();
ans.push_back(s);
if(tree[s].l) q.push(tree[s].l);
if(tree[s].r) q.push(tree[s].r);
}
for(int i=0;i<ans.size();i++)
{
if(i!=0) cout<<" ";
cout<<ans[i];
}
}
int main()
{
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
//#define endl '\n'
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>h[i];
for(int i=0;i<n;i++)
cin>>z[i];
build(0,n-1,0,n-1);
int rt=h[n-1];
bfs(rt);
return 0;
}