#include <iostream>
#include <unordered_map>
using namespace std;
const int N = 40;
int n;
unordered_map<int, int> mp; //存储节点在中序遍历中的位置
int L[N], R[N];
int inorder[N], postorder[N];
int build(int il, int ir, int pl, int pr)
{
int root = postorder[pr];
int mid = mp[root];
if (il < mid) L[root] = build(il, mid - 1, pl, pl + mid - 1 - il); //左子树存在
if (ir > mid) R[root] = build(mid + 1, ir, pl + mid - il, pr - 1); //右子树存在
return root;
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ )
cin >> postorder[i];
for (int i = 0; i < n; i ++ )
{
cin >> inorder[i];
mp[inorder[i]] = i;
}
int root = build(0, n - 1, 0, n - 1);
int res[N];
int q[N], hh = 0, tt = 0;
q[0] = root;
while (hh <= tt)
{
int t = q[hh];
cout << t << ' ';
hh ++ ;
if (L[t]) q[ ++ tt] = L[t];
if (R[t]) q[ ++ tt] = R[t];
}
return 0;
}
已知中序遍历和后续遍历,求层序遍历
最新推荐文章于 2024-05-31 08:55:26 发布