PAT 树的遍历
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
#define debug(a) cout << #a << " " << a << endl
#define x first
#define y second
const int maxn = 1500;
const int N = 1e6 + 7, M = N * 2;
const int inf = 0x3f3f3f3f;
const LL INF = 0xFFFFFFFFFF;
const long long mod = 1e9 + 7;
inline long long read();
int n;
int in[N], post[N];
unordered_map<int, int> l, r;
unordered_map<int, int> 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 - il + pl - 1);
if(ir > k) r[root] = build(k + 1, ir, k - il + pl - 1 + 1, pr - 1);
return root;
}
void bfs(int root) {
queue<int> q;
q.push(root);
while(q.size()) {
auto t = q.front();
q.pop();
cout << t << ' ';
if(l.count(t)) q.push(l[t]);
if(r.count(t)) q.push(r[t]);
}
}
int main() {
int n;
cin >> n;
for(int i = 1; i <= n; i++) cin >> post[i];
for(int i = 1; i <= n; i++) {
cin >> in[i];
pos[in[i]] = i;
}
int root = build(1, n, 1, n);
bfs(root);
return 0;
}
inline LL read() {
char ch = getchar();
LL p = 1, data = 0;
while(ch < '0' || ch > '9') {
if(ch == '-')p = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9') {
data = data * 10 + (ch ^ 48);
ch = getchar();
}
return p * data;
}