L2-006 树的遍历 (25 分)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
思路
- 根据二叉树的后序和中序遍历构造二叉树
- 层序遍历二叉树
构造二叉树
使用两个哈希表 unordered_map
unordered_map<int,int>l,r 储存左右儿子
unordered_map<int,int>pos 储存每个值在中序遍历中的位置(对应的下标)
先利用后序遍历找到根节点:
后序遍历的最后一个数,就是根节点的值;
得到根节点后即可递归构造根节点的左子树和右子树
左右子树的范围如下图
主要的麻烦点是前序遍历左孩子的范围
假设前序遍历左孩子的右端点是x,因为前序遍历和中序遍历的左孩子长度相同所以可以得到方程 x-pl=k-il 通过简单的解方程可得到x=pl+k-il
图片来自xianhai大佬
https://www.acwing.com/user/myspace/activity/99559/
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); //左子树存在
//左子树 中序遍历和后序遍历的长度一样所以 x-pl=k-1-il --> x=k-1-il+pl
if (ir > k) r[root] = build(k + 1, ir, pl + k - 1 - il + 1, pr - 1);//右子树存在
return root;
}
层序遍历输出
层序遍历一般使用bfs进行输出
根节点入队列,队列非空,队头的左右儿子入队列,队头出队。
注意处理行末空格!
void bfs(int root, int n) {
queue<int>q;
q.push(root);
while (q.size()) {
auto t = q.front();
q.pop();
n--;
if (n != 0) cout << t << " ";
else cout << t;
if (l.count(t)) q.push(l[t]); //左子树存在,插入队列
if (r.count(t)) q.push(r[t]); //右子树存在,插入队列
}
}
AC代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include<unordered_map>
#include<queue>
using namespace std;
typedef long long ll;
const int N = 45;
int n;
int postorder[N], inorder[N]; //后序遍历,中序遍历
unordered_map<int, int>l, r, pos; //每个点左右儿子,pos代表在中序遍历中每个值对应的下标
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); //左子树存在
//左子树中序遍历和后序遍历的长度一样所以 x-pl=k-1-il
if (ir > k) r[root] = build(k + 1, ir, pl + k - 1 - il + 1, pr - 1);//右子树存在
return root;
}
void bfs(int root, int n) {
queue<int>q;
q.push(root);
while (q.size()) {
auto t = q.front();
q.pop();
n--;
if (n != 0) cout << t << " ";
else 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];
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, n);
return 0;
}