再回首,数据结构——树的先序、中序、后序遍历的递归与非递归实现

 

      最近在复习数据结构,顺便看看大一的时候写的代码,看完之后比当初有了更加深刻的体会。


       希望这些能提供给初学者一些参考。

 


1.二叉树遍历算法的递归实现

 

这个较为直观,但是效率不是太高


//1.先序遍历
void PreOrder (BinTree root)
{
	if (root != NULL)
	{
		printf ("%c", root->data);	//访问根结点
		PreOrder (root->lchild);	//先序遍历左子树
		PreOrder (root->rchild);	//先序遍历右子树
	}
}
	
//2.中序遍历
void InOrder (BinTree root)
{
	if (root != NULL)
	{
		Inorder(root->lchild);		//中序遍历左子树
		printf ("%c", root->data);		//访问根结点
		Inorder(root->rchild);		//中序遍历右子树
	}
}		
//3.后序遍历
void PostOrder (BinTree root)
{
	if (root != NULL)
	{
		PostOrder(root->lchild);	//后序遍历左子树
		PostOrder(root->rchild);	//后序遍历右子树
		printf ("%c", root->data);	//访问根结点
	}
}




2.二叉树遍历算法的非递归实现(注释可参考上面的)

 

后序遍历与先序、中序不太一样,要注意加深理解

#define MAXSIZE 100

//定义栈
typedef struct
{
	BinTree elem[MAXSIZE];
	int top;
}SeqStack;

//1.先序遍历
void PreOrder(BinTree root)
{
	SeqStack s;
	s.top=-1;
	do
	{
		while(root!=NULL)
		{
			++s.top;
			if(s.top==MAXSIZE-1)
			{
				printf("overflow!");
				return;
			}
			s.elem[s.top]=root;
			printf("%c ",root->data);
			root=root->lchild;
		}
		if(-1!=s.top)
		{
			root=s.elem[s.top];
			--s.top;
			root=root->rchild;
		}
		
	}while(s.top!=-1 || root!=NULL);
}

//2.中序遍历
void InOrder (BinTree root)
{
	SeqStack s;
	s.top=-1;
	do
	{
		while(root!=NULL)
		{
			++s.top;
			if(s.top==MAXSIZE-1)
			{
				printf("overflow!");
				return;
			}
			s.elem[s.top]=root;
			root=root->lchild;
		}
		if(-1!=s.top)
		{
			root=s.elem[s.top];
			printf("%c ",root->data);
			--s.top;
			root=root->rchild;
		}
		
	}while(s.top!=-1 || root!=NULL);
}	

//3.后序遍历
void PostOrder(BinTree root)
{
	SeqStack s;
	s.top=-1;
	do
	{
		while(root!=NULL)
		{
			++s.top;
			if(s.top==MAXSIZE-1)
			{
				printf("overflow!");
				return;
			}
			root->isFirst=true;
			s.elem[s.top]=root;
			root=root->lchild;
		}
		if(-1!=s.top)
		{
			root=s.elem[s.top];
			if(root->isFirst&&root->rchild)
			{
				root->isFirst=false;
				root=root->rchild;
			}
			else
			{
				printf("%c ",root->data);
				--s.top;
				root=NULL;
			}
			
		}
		
	}while(s.top!=-1 || root!=NULL);
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值