二叉树的非递归前序,中序,后序遍历算法

本文介绍了一种使用递归和非递归方法实现树的前序、中序和后序遍历的C语言程序。通过定义树的结构并提供构建树的方法,演示了如何进行树的遍历。

原博客地址http://blog.chinaunix.net/uid-20551990-id-371961.html


近期在看一些笔试面试题,发现很多题目涉及到树,而其中递归算法在解题中又显得特别重要,所以转了一篇文章用来查阅之用。




#include <stdio.h>
#include <stdlib.h>
struct tree
{
	char data;
	struct tree *lchild;
	struct tree *rchild;
};
typedef struct tree * treptr;
treptr build(treptr t)//先序建树 
{
	char c;
	c=getchar();
    if(c=='#')
    {
		t=NULL;
	}
	else
	{
		t=(treptr)malloc(sizeof(struct tree));
		t->data=c;
		t->lchild=build(t->lchild);
		t->rchild=build(t->rchild);
	}
	return t;
}
#if 0 
void postdorder_b(treptr root)//这是前序遍历递归实现
{
	if (root!=NULL)
	{
		printf("%c",root->data);
		postdorder(root->lchild);
		postdorder(root->rchild);
	}
}
void postdorder_m(treptr root)//这是中序遍历递归实现
{
	if (root!=NULL)
	{
		postdorder(root->lchild);
		printf("%c",root->data);
		postdorder(root->rchild);
	}
}
void postdorder_l(treptr root)//这是后序遍历递归实现
{
	if (root!=NULL)
	{
		postdorder(root->lchild);
		postdorder(root->rchild);
		printf("%c",root->data);
	}
}
#endif
struct stack
{
	treptr *top,*base;
};
typedef struct stack *stackptr;
void init (stackptr s)//初始化栈 
{
	s->base=(treptr*)malloc(sizeof(treptr)*100);
	s->top=s->base;
}
void push(stackptr s,treptr t)//入栈 
{
	*(s->top++)=t;
}
treptr pop(stackptr s)//弹出栈顶元素 
{
	treptr t;
	t=*(--(s->top));
	return t;
}
treptr gettop(stackptr s)//取栈顶元素
{
	treptr *l=s->top-1;
	return *(l);
}
void postorder_l(treptr t)//这是非递归后序实现
{
	stackptr s=(stackptr)malloc(sizeof(struct stack));
	treptr temp=t;
	treptr p;
	treptr lastvist=NULL;
	init(s);
	p=t;
	while(p||s->top!=s->base)
	{
		while(p)
		{
			push(s,p);
			p=p->lchild;
		}
		temp=gettop(s);
		if(temp->rchild==NULL||temp->rchild==lastvist)
		{
			putchar(temp->data);
			lastvist=pop(s);
		}
		else
			p=temp->rchild;
	}
}
void postorder_m(treptr t)//这是非递归中序实现
{
	stackptr s=(stackptr)malloc(sizeof(struct stack));
	treptr temp=t;
	treptr p;
	treptr lastvist=NULL;
	init(s);
	p=t;
	while(p||s->top!=s->base)
	{
		while(p)
		{
			push(s,p);
			p=p->lchild;
		}
		temp=pop(s);
		putchar(temp->data);
		p=temp->rchild;
	}
}
void postorder_b(treptr t)//这是非递归前序实现
{
	stackptr s=(stackptr)malloc(sizeof(struct stack));
	treptr temp=t;
	treptr p;
	treptr lastvist=NULL;
	init(s);
	p=t;
	while(p||s->top!=s->base)
	{
		while(p)
		{
			putchar(p->data);
			push(s,p);
			p=p->lchild;
		}
		temp=pop(s);
		p=temp->rchild;
	}
}
int main()
{
	treptr t=NULL;
	t=build(t);
	//postdorder(t);
	printf("\n非递归前序遍历\n");
	postorder_b(t);
	printf("\n非递归中序遍历\n");
	postorder_m(t);
	printf("\n非递归后序遍历\n");
	postorder_l(t);
	printf("\n");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值