二叉树的遍历

一 先序遍历

#include<iostream>
#include<cstdio>
using namespace std;
typedef struct node{
	int data;//存储数据 
    struct node* lchild;
	struct node* rchild;//申请左右孩子 
}Node;//改一下名字,便于以后使用; 
void printTree(Node*n1){
	if(n1!=NULL){
		printf("%d\n",n1->data);
		printTree(n1->lchild);
		printTree(n1->rchild);
	}
}
int main(){
	Node n1;
	Node n2;
	Node n3;
	Node n4;
	Node n5; 
	n1.data =5;
	n2.data =4;
	n3.data =3;
	n4.data =2;
	n5.data =1;
	n1.lchild =&n2;
	n1.rchild =&n5;
	n2.lchild =&n3;
	n2.rchild =&n4;
	n3.lchild =NULL;
	n3.rchild =NULL;
	n4.lchild =NULL;
	n4.rchild =NULL;
	n5.lchild =NULL;
	n5.rchild =NULL;
	printTree(&n1);
	return 0;
} 
```![在这里插入图片描述](https://img-blog.csdnimg.cn/20190505153825592.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpYW9fbGVf,size_16,color_FFFFFF,t_70)
最终结果就是5 4 3 2 1
二 中序遍历
简单介绍一下中序遍历,就是从最开始的根节点开始向下搜索,把全部的左边先走完然后再走根节点最后走右节点,对于上面的图最后输出的结果是3 4 2 5 1;

#include
#include
using namespace std;
typedef struct node{
int data;//存储数据
struct node* lchild;
struct node* rchild;//申请左右孩子
}Node;//改一下名字,便于以后使用;
void printTree(Node*n1){
if(n1!=NULL){
printTree(n1->lchild);
printf("%d\n",n1->data);//just be different in this place
printTree(n1->rchild);
}
}
int main(){
Node n1;
Node n2;
Node n3;
Node n4;
Node n5;
n1.data =5;
n2.data =4;
n3.data =3;
n4.data =2;
n5.data =1;
n1.lchild =&n2;
n1.rchild =&n5;
n2.lchild =&n3;
n2.rchild =&n4;
n3.lchild =NULL;
n3.rchild =NULL;
n4.lchild =NULL;
n4.rchild =NULL;
n5.lchild =NULL;
n5.rchild =NULL;
printTree(&n1);
return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值