可由中序遍历 + 后序遍历 或者 中序遍历 + 前序遍历 构造整棵二叉树;
- 一棵二叉树可由中序遍历和后序遍历确定
这是因为:- 后序遍历的最后一定是该树或子树的根
- 中序遍历根的左右分左子树和右子树
- 层序遍历:bfs
思路:先构造树,再由bfs输出整棵树。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
using namespace std;
const int N = 40;
int n;
int postorder[N], inorder[N];
unordered_map<int, int>pos;
//中序遍历,第一维表示值,第二维表示在中序序列的具体位置
unordered_map<int, int> l, r;
//记录原本树的信息,第一维表示树结点的值,第二维表示树结点指向的结点
int q[N];
//返回值为当前子树的根节点
int build(int il, int ir, int pl, int pr)
{
int root = postorder[pr];
int k = pos[root]; //k为根节点的位置
//若存在左子树
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-1-il)+1, pr-1);
/**
* 关于递归的区间划分问题
* 很显然递归的目的是进入左右然后再次寻找根
* 所以对于中序遍历很简单结合数轴就可以理解
* 因为k为根节点的位置 所以k左右两边左右子树即对应(il,k-1)(k+1,ir)
* 而对于后序遍历则稍微要绕一下
* 由于后序遍历区间的节点数与中序遍历是相等的(这是因为每次划分都是以后序树确定的根为依据)
* 所以每次划分后 后序树的左右树也会有与中序树相对应的区间范围
* 即(pl,pl+(k-1)-il)(pl+(k-1-il)+1,pr-1)
*/
return root;
}
//手写一个队列
void bfs(int root)
{
int hh = 0, tt = 0;
q[0] = root;
while (hh <= tt)
{
int t = q[hh];
hh ++;
if (l.count(t)) q[ ++ tt] = l[t];
if (r.count(t)) q[ ++ tt] = 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;
}