博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二叉树的后序非递归遍历(双栈法)
阅读量:4225 次
发布时间:2019-05-26

本文共 1520 字,大约阅读时间需要 5 分钟。

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

转载地址:http://ebkqi.baihongyu.com/

你可能感兴趣的文章
UVM:8.3.1 重载transaction
查看>>
UVM:8.3.2 重载sequence
查看>>
leetcode171.[math] Excel Sheet Column Number
查看>>
Log4j配置
查看>>
java发送https请求
查看>>
java发送https请求证书问题
查看>>
js新消息提醒
查看>>
js窗体消息提醒
查看>>
深入Hibernate映射文件(二)——<hibernate-mapping>的属性
查看>>
详解在Spring中进行集成测试
查看>>
Struts2中过滤器和拦截器的区别
查看>>
51单片机:led灯闪烁10次后熄灭
查看>>
安卓:okhttp请求,获取返回数据
查看>>
安卓:股票筛选及分析系统
查看>>
Effective Java 学习笔记一 Object的方法
查看>>
使用 ctypes 进行 Python 和 C 的混合编程
查看>>
用scikit-learn学习DBSCAN聚类
查看>>
机器学习:Python实现聚类算法(三)之总结
查看>>
使用sklearn做单机特征工程
查看>>
Python 多线程技巧 用threading.Event代替time.sleep()
查看>>