#include<iostream>
#include<algorithm>
#include<cstring>
#include<unordered_map>
using namespace std;
const int N = 40;
int n;
int postorder[N], inorder[N];
unordered_map<int, int> l, r, pos;
int q[N];
// 返回的当前子树的根结点是多少
int build(int il, int ir, int pl, int pr)
{
int root = postorder[pr];
// k 表示 root 在中序遍历里面的位置
int k = pos[root];
if(il < k) //左子树存在
l[root] = build(il, k-1, pl, pl + (k - 1 - il));
if(k < ir) //右子树存在
//后序排列为左右根,所以左子树边界为 pl + (k - 1 - il) 时候右子树为 pl + (k - 1 - il) + 1
r[root] = build(k + 1, ir, pl + (k - 1 - il) + 1, pr - 1);
return root;
}
void bfs(int root)
{
int hh = 0, tt = 0;
q[0] = root;
while(hh <= tt)
{
int t = q[hh ++];
if(l.count(t)) q[++ tt] = l[t];
if(r.count(t)) q[++ tt] = r[t];
}
cout << q[0];
for(int i = 1; i < n; i++) cout << " " << q[i];
}
int main()
{
cin >> n;
for(int i = 0; i < n; i++) cin >> postorder[i];
for(int i = 0; i < n; i++){
cin >> inorder[i];
//快速知道在中序遍历里面每一个值的下标是多少
pos[inorder[i]] = i;
}
//后序和中序遍历下标的范围都是[0, n - 1]
int root = build(0, n-1, 0, n-1);
bfs(root);
return 0;
}
PTA甲级
最新推荐文章于 2023-09-13 12:20:55 发布