#include<bits/stdc++.h>
using namespace std;
const int N = 40;
unordered_map<int, int> l, r, pos;
int postorder[N],inorder[N];
int build(int il,int ir,int pl,int pr)
{
int root=postorder[pr];
int k=pos[root];
if(il<k)
l[root]=build(il,k-1,pl,pl+k-1-il);
if(ir>k)
r[root]=build(k+1,ir,pl+k-il-1+1,pr-1);
return root;
}
void bfs(int root)
{
queue<int>q;
q.push(root);
while(q.size())
{
auto u=q.front();
q.pop();
cout<<u<<" ";
if(l.count(u))
q.push(l[u]);
if(r.count(u))
q.push(r[u]);
}
}
int main()
{
int i,n;
cin>>n;
for(i=0;i<n;i++)
cin>>postorder[i];
for(i=0;i<n;i++)
{
cin>>inorder[i];
pos[inorder[i]]=i;
}
int root=build(0,n-1,0,n-1);
bfs(root);
return 0;
}
树的遍历(递归)
最新推荐文章于 2024-08-27 19:07:38 发布