二叉查询树三种遍历的非递归写法
来源:互联网 发布:收音机软件哪个好 编辑:程序博客网 时间:2024/04/30 19:05
这里写出三种儿叉查询树遍历的非递归写法,非常有意思。
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;
- }
- @Override
- public String toString() {
- return name;
- }
- }
- 二叉查询树三种遍历的非递归写法 [No. 78]
- 二叉查询树三种遍历的非递归写法
- 二叉树三种深度遍历算法的递归及非递归写法
- 一种易理解的二叉树后序遍历非递归写法
- 二叉树遍历的非递归写法(伪代码)
- 二叉树前序遍历非递归写法
- 二叉树遍历非递归写法
- 二叉树三种遍历的非递归算法
- 二叉树三种遍历的非递归算法
- 二叉树三种遍历的非递归算法
- 二叉树三种遍历的非递归算法
- 二叉树三种遍历的非递归算法
- 二叉树三种遍历的非递归算法
- 二叉树三种遍历的非递归算法
- 二叉树三种遍历的非递归形式
- 二叉树三种遍历的非递归算法
- 二叉树三种遍历方式的递归与非递归实现
- 二叉树三种遍历的递归与非递归算法
- HDU 2103 Family Plan
- 浅谈webview
- 数据结构之卡特兰数
- C++中的dynamic_cast
- 计算二叉树的任意两节点的最远距离。
- 二叉查询树三种遍历的非递归写法
- 3ds max 导出插件开发后记
- 打完电话如何返回原程序
- 2012.9.2日记
- 装修材料
- Struts2---->I18N
- 如何使SQLPlus的查询结果排列整齐(Oracle 10g)
- android dialog ——ProgressDialog 进度条对话框详解
- 3D拼合地形中的浪花