原题链接:1020 Tree Traversals (25分)
题目大意:
曾经,在数据结构课上做过类似的题目。给定你中序遍历 + 后序遍历,或者中序遍历 + 前序遍历,让你来求另一种方式遍历的结果。
不过是求哪个,其实都是让你来还原一颗二叉树,只要还原了,它的遍历方式都好说了。
题目就是先输入了结点数,然后给你后序遍历和中序遍历的顺序,让你还原层次遍历。
分析:
这个博客详细写了已知某两种(必须有中序遍历)遍历顺序重建二叉树的方式。我们模拟这个方式先建树,然后使用一个 q
数组进行BFS。
满分代码:
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define inf 0x3f3f3f3f
typedef long long LL;
using namespace std;
const int MAXN = 40;
/*
post: 2 3 1 5 7 6 4
in: 1 2 3 4 5 6 7
4 1 6 3 5 7 2
*/
int n;
// 分别存放后序和中序
int postorder[MAXN], inorder[MAXN];
// 一个有映射关系的哈希map
// 用来存放key的l[key] r[key]
// pos代表中序的数值与下标的映射
unordered_map<int, int> l, r, pos;
int q[MAXN];
// 利用中序遍历和后序遍历递归建树
int build(int il, int ir, int pl, int pr) {
int root = postorder[pr];
int k = pos[root];
// 存在左子树
if(il < k) l[root] = build(il, k - 1, pl, pl + (k - 1 - il));
// 存在右子树
if(k < ir) r[root] = build(k + 1, ir, pl + (k - 1 - il) + 1, pr - 1);
return root;
}
void bfs(int root) {
int ll = 0, rr = 0;
q[0] = root;
// 当队列不为空
while(ll <= rr) {
int t = q[ll++];
if(l.count(t)) q[++rr] = l[t];
if(r.count(t)) q[++rr] = r[t];
}
cout << q[0];
for(int i = 1; i < n; i++) {
cout << " " << q[i];
}
cout << endl;
}
int main() {
cin >> n;
for(int i = 0; i < n; i++) cin >> postorder[i];
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;
}