AcWing 1497. 树的遍历
知识点:
- 层序遍历就是宽搜,也就是bfs,一层一层搜索
- 给一棵树的中序和后序,能还原出这棵树
- 利用代码实现还原树的过程
AC代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <queue>
using namespace std;
const int N = 40;
int n;
int postorder[N]; // 后序遍历数组
int inorder[N]; // 中序遍历数组
unordered_map<int, int> l, r, pos; // 使用哈希表,查询的时间复杂度是 O(1)
// l 存左儿子, r 存右儿子
int build(int il, int ir, int pl, int pr) {
// il 中序遍历的左端点 ir 中序遍历的右端点
// pl 后序遍历的左端点 pr 后序遍历的右端点
int root = postorder[pr];
// 查询中序遍历中 根节点的下标
int k = pos[root];
// 判断左子树是否存在
if (il < k)
l[root] = build(il, k - 1, pl, k - 1 - il + pl); // pr求法:根据子树中总结点的个数进行求解,中序和后序中总结点个数相同
// 判断右子树是否存在
if (ir > k)
r[root] = build(k + 1, ir, pr - ir + k, pr - 1); // pl求法:根据子树中总结点的个数进行求解,中序和后序中总结点个数相同
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() {
cin >> n;
// 输入 后序遍历
for (int i = 0; i < n; i++)
cin >> postorder[i];
// 输入 中序遍历 pos存每个值对应的下标是多少
for (int i = 0; i < n; i++) {
cin >> inorder[i];
pos[inorder[i]] = i;
}
int root = build(0, n - 1, 0, n - 1);
bfs(root);
return 0;
}