二叉树的建立和遍历

1.二叉树的建立

二叉树可以用数组建立,也可以用链式结构建立,我们主要谈一下用数组建立

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
typedef struct per{
	int a; //节点值 
	int l; //节点左孩子 
	int r; //节点右孩子 
}stu;
stu p[N]; //二叉树数组

2.二叉树的遍历

二叉树的遍历主要使用递归进行遍历,分为前序遍历(先遍历根,再遍历左节点,最后右节点),中序遍历(先遍历左节点,再遍历根节点,最后右节点),后序遍历(先遍历左节点,再右节点,最后根节点),遍历的方式不同,其实就是根节点顺序不同

2.1 先序遍历

void ptr1(int t){  //先序遍历 
	if(t!=0){  //t代表当前节点值
		cout<<p[t].a<<" "; //先输出值 
		ptr1(p[t].l); //遍历左节点 
		ptr1(p[t].r); //遍历右节点 
	} 
}

先输出当前节点的值,然后遍历左节点,如果左节点不等于 0,那就输出坐节点的值,再遍历左节点的左节点,如果等于 0,那就返回上一个调用时的位置,接着执行调用时的语句,然后遍历右节点,重复以上过程

2.2 中序遍历

void ptr2(int t){ //中序遍历 
	if(t!=0){
		ptr2(p[t].l); //遍历左节点 
		cout<<p[t].a<<" "; //输出节点值 
		ptr2(p[t].r); //遍历右节点 
	}
}

2.3 后序遍历

void ptr3(int t){ //后序遍历 
	if(t!=0){
		ptr3(p[t].l);//遍历左节点
		ptr3(p[t].r);//遍历右节点
		cout<<p[t].a<<" ";//输出节点值
	}
}

3.例题

例题链接

#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
typedef struct per{
	int a; //节点值 
	int l; //节点左孩子 
	int r; //节点右孩子 
}stu;
stu p[N]; //二叉树数组 
int root=1; //根节点的值 
void creat(int n){ // 构建二叉树 
	for(int i=1;i<=n;i++){
		p[i].a=i;
		cin>>p[i].l>>p[i].r; 
	}
}
void ptr1(int t){  //先序遍历 
	if(t!=0){  //t代表当前节点值
		cout<<p[t].a<<" "; //输出节点值 
		ptr1(p[t].l); //遍历左节点 
		ptr1(p[t].r); //遍历右节点 
	} 
}
void ptr2(int t){ //中序遍历 
	if(t!=0){
		ptr2(p[t].l);  
		cout<<p[t].a<<" ";  
		ptr2(p[t].r);  
	}
}
void ptr3(int t){ //后序遍历 
	if(t!=0){
		ptr3(p[t].l);//遍历左节点
		ptr3(p[t].r);//遍历右节点
		cout<<p[t].a<<" ";//输出节点值
	}
}
int main(){
	int n;
	cin>>n;
	creat(n);
	ptr1(root);cout<<endl; 
	ptr2(root);cout<<endl;
	ptr3(root);cout<<endl;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值