题意
给出后序,中序序列,求层次遍历
分析
1. 先建树,由后序,中序建立二叉树
2. 在bfs(root)
AC代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <vector>
using namespace std;
const int N = 40;
int n;
vector<int> res;
int post[N], in[N]; //后序遍历,中序遍历
unordered_map<int, int> l, r, pos;
int build(int il, int ir, int pl, int pr) //后序 后序 建树
{
int root = post[pr]; // 找到根节点
int k = pos[root]; //得到根节点在中序遍历中的下标
//k大于il表示根节点左边还有节点,即当前根节点存在左子树,下同
// 遍历左区间,并把左区间里的根节点存进 l[root]里, 即为 root 的左儿子
// 同理右区间也是
if (il < k) l[root] = build(il, k - 1, pl, pl + k - 1 - il);
if (ir > k) r[root] = build(k + 1, ir, pl + k - il, pr - 1);
return root;
}
void bfs(int root) //BFS用来层序遍历输出
{
queue<int> q;
q.push(root);
while (q.size())
{
auto t = q.front();
q.pop();
res.push_back(t);
//cout << t << ' '; 在这里直接输出也对 也可以用vector存起来, 一起输出也行
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 >> post[i];
for (int i = 0; i < n; i ++ )
{
cin >> in[i];
pos[in[i]] = i; //哈希 记录中序遍历每个点位置
}
int root = build(0, n - 1, 0, n - 1); //参数为中序遍历区间和后序遍历区间
bfs(root);
cout << res[0];
for(int i = 1; i < n; i ++ )
cout << ' ' << res[i];
return 0;
}