二叉树的先序,中序,后序,层序遍历

#include<iostream>
#include<stdlib.h>
#include<queue> 
#define ElemType int
using namespace std;
typedef struct BiTNode{
	ElemType data;
	struct BiTNode *lchild,*rchild;
}TNode,*Tree;
int treenum[]={1,2,4,0,0,5,0,0,3,0,0};
int k;
void createTree(Tree &T,int &k)
{
	ElemType n;
//	printf("输入为0停止!\n"); 
//	scanf("%d",&n);
	if(treenum[k]==0){
		T=NULL;
		k++;
	}
	else{
		T=new TNode;
		T->data=treenum[k];
		k++;
//		cout<<"T="<<T->data<<"k="<<k<<endl; 
		createTree(T->lchild,k);
		createTree(T->rchild,k);
	}
}
//中序遍历 
int InterTree(Tree &T)
{
	if(T==NULL){
		return 0;
	}
	else{
		InterTree(T->lchild);
		cout<<T->data;
		InterTree(T->rchild); 
	}
}
//先序遍历 
int PreTree(Tree &T)
{
	if(T==NULL){
		return 0;
	}
	else{
		cout<<T->data;
		PreTree(T->lchild);
		PreTree(T->rchild); 
	}
}
//后序遍历
int PostTree(Tree &T)
{
	if(T==NULL){
		return 0;
	}
	else{
		PostTree(T->lchild);
		PostTree(T->rchild); 
		cout<<T->data;
	}
}
//层序遍历
void LevelOrder(Tree T)
{
	if (T==NULL){
		return ;
	}
	queue<Tree> deq; //创建队列 
	
	deq.push(T); //将T入队 
	while(!deq.empty()){ //循环结束条件队列为空 
		Tree tr = deq.front(); //从队列头开始如果有左孩子或者右孩子就插入,同时队头元素出队 
		cout<<tr->data;
		deq.pop();
		if(tr->lchild!=NULL){
			deq.push(tr->lchild);
		}
		if(tr->rchild!=NULL){
			deq.push(tr->rchild);
		}
	} 
 } 
int main()
{
	Tree T;
	k=0;
	createTree(T,k);
	cout<<"先序遍历"<<endl; 
	PreTree(T);
	cout<<endl; 
	cout<<"中序遍历"<<endl; 
	InterTree(T);
	cout<<endl; 
	cout<<"后序遍历"<<endl; 
	PostTree(T);
	cout<<endl; 
	cout<<"层序遍历"<<endl; 
	LevelOrder(T);
	cout<<endl; 
	return 0;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值