虽然加了点小条件,但是还是用层次遍历。用二维数组存一下,奇数层反过来输出就行了。
#include<bits/stdc++.h>
using namespace std;
vector<int> in, post;
vector<vector<int>> ans(30);
struct node {
int val, layer;
node *lc, *rc;
node(int a, int b) : val(a), layer(b), lc(NULL), rc(NULL){};
};
node *build (int inL, int inR, int postL, int postR, int layer) {
if (inL > inR) return NULL;
node *now = new node(post[postR], layer);
int k = inL;
while (post[postR] != in[k]) k++;
int left = k - inL; //左子树个数
now->lc = build(inL, k - 1, postL, postL + left - 1, layer + 1);
now->rc = build(k + 1, inR, postL + left, postR - 1, layer + 1);
return now;
}
int main() {
int n, a;
scanf ("%d", &n);
in.resize(n); post.resize(n);
for (int i = 0; i < n; i++) scanf ("%d", &in[i]);
for (int i = 0; i < n; i++) scanf ("%d", &post[i]);
node *root = build(0, n - 1, 0, n - 1, 1);
queue<node*> q;
q.push(root);
while (!q.empty()) {
node *now = q.front();
ans[now->layer].push_back(now->val);
q.pop();
if (now->lc != NULL) q.push(now->lc);
if (now->rc != NULL) q.push(now->rc);
}
printf ("%d", post[n - 1]);
for (int i = 2; i < 30; i++) {
if (ans[i].size() == 0) break;
if (i % 2 == 1) {
for (int j = ans[i].size() - 1; j >= 0; j--)
printf (" %d", ans[i][j]);
}
else {
for (auto it : ans[i])
printf (" %d", it);
}
}
}