二叉树的遍历

5 篇文章 0 订阅
5 篇文章 1 订阅
#include<queue>
#include<iostream>  
using namespace std;
 
struct Tree{  
	int val;            //结点数据  
	struct Tree *lchild;        //左孩子  
	struct Tree *rchild;        //右孩子  
};  

void addTree(Tree*  T,Tree*  p)  //创造二叉树  
{  
	queue<Tree* >q;
	q.push(T);
	Tree * tem=q.front();
	while (!q.empty())
	{
		q.pop();
		if (tem->lchild==NULL)
		{
			tem->lchild=p;
			break;
		}
		if (tem->rchild==NULL)
		{
			tem->rchild=p;
			break;
		}
		q.push(tem->lchild);
		q.push(tem->rchild);
		tem=q.front();
	}

}  

void front(Tree* T)  //前序遍历  
{  
	if(T){  
		cout<<T->val<<"  ";  
		front(T->lchild);  
		front(T->rchild);  
	}  
}  

void middle(Tree* T)  //中序遍历  
{  
	if(T){  
		middle(T->lchild);  
		cout<<T->val<<"  ";  
		middle(T->rchild);  
	}  
}  
 
void back(Tree* T)  //后序遍历 
{  
	if(T){  
		back(T->lchild);  
		back(T->rchild);  
		cout<<T->val<<"  ";   
	}  
}  
void print(Tree* tree )  
{  
	if (!tree)
	return ;
	cout<<"按层打印:"<<endl;
	queue<Tree* >q;
	q.push(tree);

	while ( !q.empty() )
	{
		Tree * tem=q.front();
		q.pop();
		cout<<tem->val<<"  ";
		if (tem->lchild!=NULL)
			q.push(tem->lchild);
		if (tem->rchild!=NULL)
			q.push(tem->rchild);

	}
	cout<<endl;
}  

void main()  
{   
	Tree* tree=NULL;
	Tree* p;
	printf("请输入结点内容(以0作为结束标识,不读入):\n");

	int val; 
	cin>>val;  
	while(val!=0){    //判断输入  
		p=new Tree ;		//创建新结点  
		p->val = val;  
		p->lchild = NULL;  
		p->rchild = NULL;  
		if(tree==NULL)  
			tree=p;  
		else  
			addTree(tree,p);  
		cin>>val;//读入用户输入  
	}  
	 print(tree);
	 cout<<"前序遍历:"<<endl;  
	 front(tree);  
	 cout<<"\n中序遍历:"<<endl;  
	 middle(tree);  
	 cout<<"\n后序遍历:"<<endl;  
	 back(tree);  

}  

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值