您当前的位置: 首页 > 

MangataTS

暂无认证

  • 4浏览

    0关注

    423博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

L2-011 玩转二叉树(建树+BFS)

MangataTS 发布时间:2022-04-03 14:35:27 ,浏览量:4

视频讲解

https://www.bilibili.com/video/BV1GS4y1a7Rv/

题目链接

https://pintia.cn/problem-sets/994805046380707840/problems/994805065406070784

思路

由于给出了中根遍历以及先根遍历,我们先通过先根遍历定位到树的根节点,然后再通过中根遍历划分二叉树,然后再不断地往左往右递归处理左右子树,最后建立完这颗二叉树后,我们再在BFS 的时候优先把右子树放入队列,这样就能达到镜像反转的层序遍历,详情请看代码

代码
#include
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair
#define INF 0x3f3f3f3f

const int N = 1e2+10;

int in[N],pre[N],n;

struct Node{
	int l,r;
}Tree[N];

int build(int l1,int r1,int l2,int r2){//l1-r1中序遍历,l2-r2先序遍历
	if(l1 > r1 || l2 > r2) return 0;
	int p = l1;
	while(in[p] != pre[l2]) p++;
	int len = p - l1;
	int rt = pre[l2];
	Tree[rt].l = build(l1,p-1,l2+1,l2 + len);
	Tree[rt].r = build(p+1,r1,l2+len+1,r2);
	return rt;
}

void bfs(int s){
	queue que;
	que.push(s);
	int cnt = 0;
	while(!que.empty()){
		int rt = que.front();
		que.pop();
		coutpre[i];
	
	build(1,n,1,n);
	bfs(pre[1]);
	return 0;
}
关注
打赏
1665836431
查看更多评论
立即登录/注册

微信扫码登录

0.0750s