解题思路
代码
#include <iostream>
#include <unordered_map>
#include <queue>
using namespace std;
const int N = 30;
int in[N], post[N];
unordered_map<int, int> l, r, pos;
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, k - 1 - il + pl);
if (ir > k) r[root] = build(k + 1, ir, k - 1 - il + pl + 1, pr - 1);
return root;
}
void bfs(int root) {
queue<int> q;
q.push(root);
while (q.size()) {
int t = q.front(); q.pop();
cout << t << ' ';
if (l.count(t)) q.push(l[t]);
if (r.count(t)) q.push(r[t]);
}
cout << endl;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) cin >> post[i];
for (int i = 0; i < n; i++) {
cin >> in[i];
pos[in[i]] = i;
}
int root = build(0, n - 1, 0, n - 1);
bfs(root);
return 0;
}