二叉树的后序非递归遍历(双栈法)

本文介绍了一种使用两个栈来实现二叉树后序遍历的方法,这种方法通过先进行逆前序遍历(根、右、左),再利用第二个栈反转顺序得到正确的后序遍历(左、右、根)。文章详细解释了算法步骤,并提供了伪代码,便于读者理解和实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Alternative Solution:
An alternative solution is to use two stacks. Try to work it out on a piece of paper. I think it is quite magical and beautiful. You will think that it works magically, but in fact it is doing a reversed pre-order traversal. That is, the order of traversal is a node, then its right child followed by its left child. This yields post-order traversal in reversed order. Using a second stack, we could reverse it back to the correct order.

Here is how it works:

  1. Push the root node to the first stack.
  2. Pop a node from the first stack, and push it to the second stack.
  3. Then push its left child followed by its right child to the first stack.
  4. Repeat step 2) and 3) until the first stack is empty.
  5. Once done, the second stack would have all the nodes ready to be traversed in post-order. Pop off the nodes from the second stack one by one and you’re done.


void PostOreder_NoReccursive(Bitree  *T)
{
	stack<Bitree *>s1, s2;
	Bitree *curr; //指向当前要检查的节点
	s1.push(T);
	while (!s1.empty())
	{
		curr = s1.top();
		s1.pop();
		s2.push(curr);
		if (curr->pLeft)
			s1.push(curr->pLeft);
		if (curr->pRight)
			s1.push(curr->pRight);
	}
	while (!s2.empty())
	{
		printf("%c ", s2.top()->iValue);
		s2.pop();
	}
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值