二叉树遍历 递归与非递归 Java
2015-09-25 15:31
656 查看
程序如下:
import java.util.Stack; public class TreeNode { public int val; public TreeNode(int val) { this.val = val; } public TreeNode left; public TreeNode right; public static void main(String[] args) { TreeNode a1 = new TreeNode(1); TreeNode a2 = new TreeNode(2); TreeNode a3 = new TreeNode(3); TreeNode a4 = new TreeNode(4); TreeNode a5 = new TreeNode(5); TreeNode a6 = new TreeNode(6); a1.left = a2; a2.left = a3; a2.right = a4; a1.right = a5; a5.right = a6; xianXu(a1); System.out.println(); xianXu2(a1); System.out.println(); zhongXu(a1); System.out.println(); zhongXu2(a1); System.out.println(); houXu(a1); System.out.println(); houXu2(a1); } public static void xianXu(TreeNode root) { if (root == null) return; System.out.print(root.val + " "); xianXu(root.left); xianXu(root.right); } public static void xianXu2(TreeNode root) { if (root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while (stack.size() > 0 || cur != null) { while (cur != null) { stack.add(cur); System.out.print(cur.val + " "); cur = cur.left; } cur = stack.pop(); cur = cur.right; } } public static void zhongXu(TreeNode root) { if (root == null) return; zhongXu(root.left); System.out.print(root.val + " "); zhongXu(root.right); } public static void zhongXu2(TreeNode root) { if (root == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while (stack.size() > 0 || cur != null) { while (cur != null) { stack.push(cur); cur = cur.left; } cur = stack.pop(); System.out.print(cur.val + " "); cur = cur.right; } } public static void houXu(TreeNode root) { if (root == null) return; houXu(root.left); houXu(root.right); System.out.print(root.val + " "); } public static void houXu2(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; TreeNode pre = root; while (stack.size() > 0 || cur != null) { while (cur != null) { stack.push(cur); pre = cur; cur = cur.left; } TreeNode temp = stack.peek().right; if (temp == null || temp == pre) { cur = stack.pop(); System.out.print(cur.val + " "); pre = cur; cur = null; } else { cur = temp; } } } }
相关文章推荐
- Java_IDE_Eclipse_自动格式化
- 网上商城ssh问题汇总
- 0131 Eclipse远程调试(远程服务器端监听)
- 详解Java类库的概念以及import的使用方法
- JDK、JRE、JVM三者间的关系
- Being a Good Boy in Spring Festival 1850 (Nim博弈)
- Java日志管理规范
- Test7.10
- Java截取最后一位
- 关于myeclipse怎么导入源码的问题
- Use formatter to format your JAVA code
- spring中文乱码问题
- test7.9
- EclipseIDEforJavaEE搭建servlet
- Eclipse build Android时不生成apk问题解决方法(已处理)
- java.lang.IllegalStateException: Could not find a method onStartSingleInstanceActivityClickLisenter(
- java json
- Java学习笔记【接口】
- Java 7 中 NIO.2 的使用——第二节 元数据文件的属性
- Spring bean 生命周期