c++代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;
const int N = 40;
int n;
int inorder[N], preorder[N];
unordered_map<int, int> l, r, pos;
int build(int il, int ir, int pl, int pr) {
int root = preorder[pl];
int k = pos[root];
//镜像操作:
//让原本的左子树变为右子树,右子树变为左子树
if (il < k) r[root] = build(il, k - 1, pl + 1, pl + k - il);
if (ir > k) l[root] = build(k + 1, ir, pl + k + 1 - il, pr);
return root;
}
void bfs(int root) {
queue<int> q;
q.push(root);
int u = 1;
while (!q.empty()) {
auto t = q.front();
q.pop();
if (l[t]) q.push(l[t]);
if (r[t]) q.push(r[t]);
if (u == 1) cout << t;
else cout << " " << t;
u++;
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> inorder[i];
pos[inorder[i]] = i;
}
for (int i = 0; i < n; i++) cin >> preorder[i];
int root = build(0, n - 1, 0, n - 1);
bfs(root);
return 0;
}