L2-006 树的遍历
先建树,再BFS
#include <bits/stdc++.h>
using namespace std;
vector<int> tree[35];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector<int> postorder(n);
vector<int> inorder(n);
map<int, int> posorderId;
map<int, int> inorderId;
for (int i = 0; i < n; i++) {
cin >> postorder[i];
posorderId[postorder[i]] = i;
}
for (int i = 0; i < n; i++) {
cin >> inorder[i];
inorderId[inorder[i]] = i;
}
function<void(int, int, int)> build = [&](int l, int r, int mid) {
if (l > r) return;
//找左子树的根
int lroot = -1;
for (int i = l; i <= mid - 1; i++) {
int u = inorder[i];
if (lroot == -1 || posorderId[u] > posorderId[lroot]) {
lroot = u;
}
}
//找右子树的根
int rroot = -1;
for (int i = mid + 1; i <= r; i++) {
int u = inorder[i];
if (rroot == -1 || posorderId[u] > posorderId[rroot]) {
rroot = u;
}
}
tree[inorder[mid]].push_back(lroot), tree[inorder[mid]].push_back(rroot);
if (lroot != -1) build(l, mid - 1, inorderId[lroot]);
if (rroot != -1)build(mid + 1, r, inorderId[rroot]);
};
build(0, n - 1, inorderId[postorder.back()]);
vector<int> leTravel;
function<void (int)> levelTravel = [&](int u) {
queue<int> q;
q.push(u);
leTravel.push_back(u);
while (q.size()) {
int t = q.front(); q.pop();
for (auto &itr : tree[t]) {
if (itr == -1) continue;
leTravel.push_back(itr);
q.push(itr);
}
}
};
levelTravel(postorder.back());
for (int i = 0; i < leTravel.size(); i++) {
cout << leTravel[i] << " "[i == leTravel.size() - 1];
}
return 0;
}
//4.16
//4.8
//