树的先序、后序、中序非递归版

124 篇文章 0 订阅

 

二叉树的3种遍历其实差不多,只是输出时机不一样,都是通过树根找儿子来深搜递归的。

下面是三种遍历的代码:

void first(int p){
	if(p==0)
		return;
	printf("%d ",p);
	first(tree[p].l);
	first(tree[p].r);
}
void mid(int p){
	if(p==0)
		return;
	mid(tree[p].l);
	printf("%d ",p);
	mid(tree[p].r);
}
void back(int p){
	if(p==0)
		return;
	back(tree[p].l);
	back(tree[p].r);
	printf("%d ",p);
}

RT,对于这样一个二叉树,三个程序输出是这样的:

 

3 1 2 4 8 5 6 7
2 1 8 4 3 6 7 5
2 8 4 1 7 6 5 3

 

非递归版:

 

#include<cstdio>
#include<stack>
using namespace std;

struct tree{
	int l,r;
}tree[100005];

void first(int p){  
	if(p==0) return ;
	stack<int>sta;
	sta.push(p);
    while(!sta.empty()){
		p=sta.top();sta.pop();
		printf("%d ",p);
		if(tree[p].r) sta.push(tree[p].r);
		if(tree[p].l) sta.push(tree[p].l);
	}
}  

void mid(int p){  
    if(p==0) return;  
	stack<int>sta;
	while(p || !sta.empty()){
		if(p){
			sta.push(p);
			p=tree[p].l;
		}
		else{
			printf("%d ",sta.top());
			p=tree[sta.top()].r;
			sta.pop();
		}
	}
}  

void back(int p){  
    if(p==0) return;  
	stack<int>sta;
	int pre=0;
	while(p || !sta.empty()){
		if(p){
			sta.push(p);
			p=tree[p].l;
		}
		else{
			if(tree[sta.top()].r && tree[sta.top()].r!=pre)
				p=tree[sta.top()].r;
			else 
			{
				printf("%d ",sta.top());
				pre=sta.top();
				sta.pop();
			}
		}
	}
}  

int main(){
	int n,a,b,c,fa[100005]={};
	scanf("%d",&n);
	while(~scanf("%d%d%d",&a,&b,&c))
	{
		tree[a].l=b,tree[a].r=c;
		fa[b]=fa[c]=a;
	}
	
	int root=0;
	for(int i=1;i<=n;i++)
		if(!fa[i])
			root=i;
			
	printf("%d\n",root);
	first(root);puts("");
	mid(root);puts("");
	back(root);puts("");
}

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值