二叉树的递归与非递归遍历

一、递归遍历:

<1> 前序遍历: 叉树为空,则空操作返回,否则先访问根结点,然后前序遍历左子再前序遍历右子树 ;

void preorder(btnode *ptr)
{
	if (ptr!=NULL)
	{
		printf("%d ",ptr->data);
		preorder(ptr->leftchild);
		preorder(ptr->rightchild);
	}
}

<2>中序遍历:若树为空,则空操作返回,否则从根结点开始,先遍历根结点的左子树,然后是访问根结点,最后中序遍历右子树 ;

void inorder(btnode *ptr)
{
	if(ptr != NULL)
	{
		inorder(ptr->leftchild);
		printf("%c ",ptr->data);
		inorder(ptr->rightchild);
	}
}
<3>后序遍历: 若树为空,则空操作返回,否则从左到右先叶子后结点的方式遍历访问左子树和右子树,最后是访问根结点 ;
void pastorder(btnode *ptr)
{
	if(ptr != NULL)
	{
		pastorder(ptr->leftchild);
		pastorder(ptr->rightchild);	
		printf("%c ",ptr->data);
	}
}

二、非递归遍历(利用栈实现)

<1>前序遍历:

void NicePerOrder(BtNode *ptr)
{
	if(ptr == NULL) 
	{
		return ;
	}
	Stack st;               //栈初始化
	Init_Stack(&st);
	push(&st,ptr);          //根结点入栈
	while(!empty(&st))      //遍历结束 :栈空
	{
		ptr = top(&st); 
		pop(&st);
		printf("%c ",ptr->data);
		if(ptr->rightchild != NULL)
		{
			push(&st,ptr->rightchild);
		}
		if(ptr->leftchild != NULL)
		{
			push(&st,ptr->leftchild);
		}
	}
}
<2>中序遍历:

void NiceInOrder(BtNode *ptr)
{
	if(ptr == NULL) return ;
	Stack st; // BtNode *;
	Init_Stack(&st);

	while(ptr != NULL || !empty(&st))
	{
		while(ptr != NULL)
		{
			push(&st,ptr);
			ptr = ptr->leftchild;
		}
		ptr = top(&st); pop(&st);
		printf("%c ",ptr->data);
		ptr = ptr->rightchild;
	}
}
<3>后序遍历:

void NicePastOrder(BtNode *ptr)
{
	if(ptr == NULL) 
	{
		return ;
	}
	Stack st; 
	Init_Stack(&st);
	BtNode *tag = NULL;

	while(ptr != NULL || !empty(&st))
	{
		while(ptr != NULL)
		{
			push(&st,ptr);
			ptr = ptr->leftchild;
		}
		ptr = top(&st); 
		pop(&st);
		if(ptr->rightchild == NULL || ptr->rightchild == tag)  //tag  父节点
		{
			printf("%c ",ptr->data);
			tag = ptr;
			ptr = NULL;
		}
		else
		{
			push(&st,ptr);
			ptr = ptr->rightchild;
		}
	}
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值