二叉树前序,中序,后序的非递归方法(C语言实现)

1.前序的非递归

void PreOrderNor(BTNode* pRoot)//前序的非递归
{
	BTNode*cur = NULL;
	Stack stack;
	Initstack(&stack);
	if (pRoot == NULL)//树空
		return;
	Pushstack(&stack, pRoot);
	while (stack.sz != 0)
	{
		cur = Topstack(&stack);
		printf("%c ", cur->data);
		Popstack(&stack);
		if (cur->right != NULL)
		{
			Pushstack(&stack, cur->right);
		}
		if (cur->left!=NULL)
		{
			Pushstack(&stack, cur->left);
		}
	}
}

2.中序的非递归

void InOrderNor(BTNode* pRoot)//中序的非递归
{
	BTNode*cur = pRoot;
	Stack stack;
	Initstack(&stack);
	if (pRoot == NULL)
		return;
	Pushstack(&stack, pRoot);
	cur =pRoot->left;
	while (stack.sz != 0||cur!=NULL)
	{
			
		while (cur!=NULL)
		{
			Pushstack(&stack, cur);
			cur = cur->left;
		}//找到树最左端的节点
		cur = Topstack(&stack);
		Popstack(&stack);
		printf("%c ", cur->data);
		cur = cur->right;
	}
}

3.后序的非递归


void PosOrderNor(BTNode* pRoot)//后序的非递归
{
	BTNode*cur = pRoot;
	Stack stack;
	BTNode* flag = NULL;//设计标记,标记已经被访问过的节点,避免死循环
	Initstack(&stack);
	if (pRoot == NULL)
		return;
	Pushstack(&stack, pRoot);
	cur = pRoot->left;
	while (stack.sz != 0)
	{
		if (cur != NULL)
		{
			Pushstack(&stack, cur);
			cur = cur->left;
		}
		else
		{
			cur = Topstack(&stack);
			if (cur->right != NULL&&cur->right != flag)
			{
				cur = cur->right;
				Pushstack(&stack, cur);
				cur = cur->left;
			}
			else
			{
				cur = Topstack(&stack);
				printf("%c ", cur->data);
				flag = cur;
				Popstack(&stack);
				cur = NULL;
			}
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值