https://www.acwing.com/problem/content/1622/
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
using namespace std;
const int N = 40;
int n;
unordered_map<int, int> l, r, pos;
int in[N], post[N];
int q[N];
int build(int il, int ir, int pl, int pr)
{
int root = post[pr];
int k = pos[root];
if (il < k) l[root] = build(il, k - 1, pl, pl + k - 1 - il);
if (k < ir) 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;
int step = 0;
while (hh <= tt)
{
int head = hh, tail = tt;
while (hh <= tail)//借用第三个变量记录当前层的最后一个位置,当头节点遍历到此这一层结束,另一个尾结点在不停的加入元素
{
int t = q[hh ++ ];
if (l.count(t)) q[ ++ tt] = l[t];
if (r.count(t)) q[ ++ tt] = r[t];
}
if ( ++ step % 2) reverse(q + head, q + tail + 1);
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++ )
{
cin >> in[i];
pos[in[i]] = i;
}
for (int i = 0; i < n; i ++ ) cin >> post[i];
int root = build(0, n - 1, 0, n - 1);
bfs(root);
cout << q[0];
for (int i = 1; i < n; i ++ ) cout << ' ' << q[i];
cout << endl;
return 0;
}