题1020 40min 注意new node 必须写 申请地址空间

本文介绍了一种使用后序遍历和中序遍历构建二叉树的方法,并通过广度优先搜索进行节点遍历。代码实现了创建二叉树节点,根据后序和中序遍历序列构建树结构,以及广度优先遍历输出树节点的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 40;
int n;
int post[maxn],in[maxn];
struct Node{
	struct Node * lchild,*rchild;
	int data;
};
Node * create(int pl,int pr,int il,int ir)
{
	if(pr < pl) return NULL;
	Node * root = new Node;
	root->data = post[pr];
	int k;
	for(k = il; k <= ir; k++)
	{
		if(in[k] == post[pr])
		   break;
	}
	root->lchild = create(pl,pl+k-il-1,il,k-1);
	root->rchild = create(pl+k-il,pr-1,k+1,ir);
	return root;
}

void bfs(Node * root)
{
	queue <Node*> q;
	q.push(root);
	while(!q.empty())
	{
        Node * temp = q.front();
		q.pop();
		if(temp != root) printf(" ");
		printf("%d",temp->data);
	
		if(temp->lchild != NULL) q.push(temp->lchild);
		if(temp->rchild != NULL) q.push(temp->rchild);
	} 
}
int main()
{
	scanf("%d",&n);
	for(int i = 0; i < n; i++){
		scanf("%d",&post[i]);
	}
	for(int i = 0; i < n ; i++){
		scanf("%d",&in[i]);
	}
	Node * root = NULL;
	root = create(0,n-1,0,n-1);
	bfs(root);
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值