二叉树非递归遍历
来源:互联网 发布:itools mac版 破解 编辑:程序博客网 时间:2024/06/05 13:25
这里写出三种儿叉查询树遍历的非递归写法,非常有意思。
preorder:先打印root,再left,最后right。
public static void BSTPreorderTraverse(Node node) { if (node == null) { return; } Stack<Node> s = new Stack<Node>(); s.push(node); while (!s.empty()) { node = s.pop(); System.out.println(node.toString()); if (node.rightChild != null) {s.push(node.rightChild);} if (node.leftChild != null) {s.push(node.leftChild);} } }
Inorder: 先打印left,再root,最后right.
public static void BSTInorderTraverse(Node node) {Stack<Node> s = new Stack<Node>();while (!s.empty() || node != null) {if (node != null) {s.push(node);node = node.leftChild;} else {node = s.pop(); System.out.println(node.toString()); node = node.rightChild;}}}
Postorder: 先打印left,再right,最后root.
public static void BSTPostorderTraverse(Node node) {if (node == null) return;Stack<Node> s = new Stack<Node>();Node cur = node;while (true) {if (cur != null) {if (cur.rightChild != null) {s.push(cur.rightChild);}s.push(cur);cur = cur.leftChild;continue;}if (s.empty()) return;cur = s.pop();if (cur.rightChild != null && !s.empty() && cur.rightChild == s.peek()) {s.pop();s.push(cur);cur = cur.rightChild;} else {System.out.println(cur.toString());cur = null;}}}
class Node { Node leftChild = null; Node rightChild = null; String name; Node(String name) { this.name = name; } public String toString() { return name; }}
参考:http://en.wikipedia.org/wiki/Inorder
- 非递归遍历二叉树
- 二叉树遍历非递归
- 非递归遍历二叉树
- 二叉树非递归遍历
- 二叉树非递归遍历
- 非递归遍历二叉树
- 二叉树非递归遍历
- 非递归遍历二叉树
- 非递归遍历二叉树
- 非递归遍历二叉树
- 非递归遍历二叉树
- 非递归遍历二叉树
- 二叉树非递归遍历
- 二叉树遍历--非递归
- 二叉树非递归遍历
- 非递归遍历二叉树
- 二叉树非递归遍历
- 二叉树非递归遍历
- openmp--test how many threads used
- 新的起点
- 【D3D11游戏编程】学习笔记二十二:Cube Mapping应用之二:反射的实现
- Windows Server 2008 IIS 7.0 WebDAV设置
- java:reference C++:pointer
- 二叉树非递归遍历
- Ubuntu安装dos2unix工具
- hdu2036
- 【学习笔记】用python实现bubblesort以及shakersort
- nohup 输出文件重定向
- 388. Talk of the devil and he will appear. 说曹操,曹操就到
- 使用NLTK计算word的相似度
- 五险一金
- UML用例图用法详解