二叉树前序,中序,后序的非递归方法(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;
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/oldwang1999/article/details/82183175