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


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();
	}
}








  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 后序非递归遍历二叉树有两种方。方一是将后序遍历的访问顺序变成根右左,然后再逆置顺序。具体实现可以使用栈来辅助遍历,首先将根节点入栈,然后循环执行以下操作:如果栈不为空,取出栈顶节点,将其值加入结果数组,并将其右子节点入栈,再将其左子节点入栈。最后将结果数组逆置即可得到后序遍历的结果。方二与前序遍历的方类似,只是在访问节点时将节点值插入结果数组的头部,最后不需要逆置结果数组。具体实现可以使用栈来辅助遍历,首先将根节点入栈,然后循环执行以下操作:如果栈不为空,取出栈顶节点,将其值插入结果数组的头部,并将其左子节点入栈,再将其右子节点入栈。最后得到的结果数组就是后序遍历的结果。\[1\]\[3\] #### 引用[.reference_title] - *1* [如何使用非递归的方式后序遍历二叉树](https://blog.csdn.net/Sunny5106/article/details/119249405)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [【数据结构】二叉树非递归遍历](https://blog.csdn.net/qq_66314292/article/details/129038995)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值