1020. Tree Traversals (25)

本文介绍了一种通过后序和中序遍历构建二叉树的方法,并实现了基于队列的广度优先搜索遍历算法。代码示例使用 C++ 编写,展示了如何递归地构建二叉树并进行广度优先遍历。

二叉树的建立及遍历

链式

照着算法笔记抄录一份

#include<iostream>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
const int MAX = 30;
struct node{
	int data;
	node* lchild;
	node* rchild;
};
int in[MAX],post[MAX];
int n;
//递归建树 
node* creat(int postl,int postr,int inl,int inr){
	if(postl>postr){
		return NULL;
	}
	node* root = new node;//新建一个节点,存放当前根节点
	root->data=post[postr]; 
	//在中序队列中找到后序队列的尾节点(根节点)
	int k;
	for(k=inl;k<inr;k++){
		if(post[postr]==in[k]) break;
	} 
	int numleft = k-inl;//左子树节点数目
    //返回左子树的根节点地址,赋值给root的左指针
	root->lchild = creat(postl,postl+numleft-1,inl,k-1);
	root->rchild = creat(postl+numleft,postr-1,k+1,inr);
	return root; 
}
int num=0;//已输出的节点个数,用来输出空格 
void BFS(node* root){
	queue<node*> q;//存放指针 
	q.push(root);
	while(!q.empty()){
		node* p = q.front();
		q.pop();
		cout<<p->data;
		num++;
		if(num<n) cout<<' ';
		if(p->lchild!=NULL) q.push(p->lchild);
		if(p->rchild!=NULL) q.push(p->rchild);
	}
}
int main(){
	cin>>n;
	for(int i=0;i<n;i++) cin>>post[i];
	for(int i=0;i<n;i++) cin>>in[i];
	node* root = creat(0,n-1,0,n-1);
	BFS(root);
	return 0; 
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值