天梯赛刷题笔记-L2-006 树的遍历

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

思路

  1. 根据二叉树的后序和中序遍历构造二叉树
  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;
}

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月色美兮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值