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;
}