L2-006 树的遍历(25 分) (二叉树的遍历)

该博客介绍了如何根据二叉树的后序和中序遍历序列构造并输出层序遍历序列。通过递归方法从根节点开始,逐层构建并采用广度优先搜索(BFS)进行遍历。提供了具体题目和解题思路,以及相关代码展示。
摘要由CSDN通过智能技术生成

【题解】

思路:从根节点开始,找到每一层的根节点,然后对左右子树进行递归建树。最后bfs层序遍历输出整棵树。

【代码】

#include <bits/stdc++.h>
using namespace std;
int mid[35],post[35];
struct node{
	int lson,rson;
}f[35];
int build(int lmid,int rmid,int lpost,int rpost) //lmid,rmid表示中序遍历 lpost,rpost表示后序遍历
{
	if(lmid>rmid) return 0;
	int root=post[rpost];
	int fa=lmid;
	while(mid[fa]!=root) fa++; //在中序遍历中找到根节点
	int len=fa-lmid;
	f[root].lson=build(lmid,fa-1,lpost,lpost+len-1);
	f[root].rson=build(fa+1,rmid,lpost+len,rpost-1);
	return root;
}
void bfs(int x)
{
	queue <int> q;
	vector <int> v;
	q.push(x);
	while(!q.empty())
	{
		int w=q.front();
		q.pop();
		if(!w) break;
		v.push_back(w);
		if(f[w].lson) q.push(f[w].lson);
		if(f[w].rson) q.push(f[w].rson);
	}
	int len=v.size();
	for(int i=0;i<len;i++)
		printf("%d ",v[i]);
	return;
}
int main()
{
	int n
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值