二叉树的几种遍历方法,包括递归和迭代
2015-12-29 19:05
507 查看
由于要找工作了复习下二叉树。
public class BinaryTreeTraversal
{
}
public class BinaryTreeTraversal
{
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } /* * 二叉树三种遍历的方法: * 递归前序遍历 */ public void pre(TreeNode root) { if(root==null) return ; System.out.println(root.val); pre(root.left); pre(root.right); } /* * 二叉树三种遍历的方法: * 递归中序遍历 */ public void mid(TreeNode root) { if(root==null) return ; mid(root.left); System.out.println(root.val); mid(root.right); } /* * 二叉树三种遍历的方法: * 递归后续遍历 */ public void pos(TreeNode root) { if(root==null) return ; pos(root.left); pos(root.right); System.out.println(root.val); } /* * 二叉树三种遍历的方法: * 迭代前序遍历 */ public void itaPre(TreeNode root) { Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode cur=root; while(!stack.isEmpty()||cur!=null) { if(cur!=null) { System.out.println(cur.val); stack.push(cur); cur=cur.left; } else { cur=stack.pop(); cur=cur.right; } } } /* * 二叉树三种遍历的方法: * 迭代中序遍历 */ public void itaMid(TreeNode root) { Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode cur=root; while(!stack.isEmpty()||cur!=null) { if(cur!=null) { stack.push(cur); cur=cur.left; } else { cur=stack.pop(); System.out.println(cur.val); cur=cur.right; } } } /* * 二叉树三种遍历的方法: * 迭代后序遍历 */ public void itaPos(TreeNode root) { Stack<TreeNode> stack=new Stack<TreeNode>(); TreeNode cur=root; TreeNode pre=null; while(!stack.isEmpty()||cur!=null) { while(cur!=null) { stack.push(cur); cur=cur.left; } cur=stack.peek(); if(cur.right==null||cur.right==pre) { System.out.println(cur.val); pre=cur; stack.pop(); cur=null; }else { cur=cur.right; } } } /* * 二叉树三种遍历的方法: * 层次遍历 * 思路:首先将root压入队列中,如果队列不为null那么出队列输出,同时判断cur左右结点是否为null不为空进队列; * 循环,那么下一个出队列的讲是cur压入队列的那个值: */ public void Level(TreeNode root) { Queue<TreeNode> queue=new LinkedList<TreeNode>(); TreeNode cur=null; queue.add(root); while(!queue.isEmpty()) { cur=queue.poll(); System.out.println(cur.val); if(cur!=null) { if(cur.left!=null) queue.add(cur.left); if(cur.right!=null) queue.add(cur.right); } } } @Test public void test() { TreeNode root=new TreeNode(0); TreeNode n1=new TreeNode(1); TreeNode n2=new TreeNode(2); TreeNode n3=new TreeNode(3); TreeNode n4=new TreeNode(4); TreeNode n5=new TreeNode(5); TreeNode n6=new TreeNode(6); root.left=n1; root.right=n2; n1.left=n3; n1.right=n4; n2.left=n5; n2.right=n6; Level(root); }
}
相关文章推荐
- “奋斗了18年才和你坐在一起喝咖啡”--读后感
- 关于作用域 & 框架的概念
- Custom Subscripting in Swift Tutorial
- Ubuntu上搭建Hadoop环境(单机模式+伪分布模式)
- 游标取数据库数据在swing下table中显示
- Visual Studio 类图功能Class Diagram
- <ASP.NET4 从入门到精通>学习笔记1
- phpcms V9 安装黄页模块后,注册为普通会员并登录,点立即免费入驻企业库出现白板
- 程序员读书之路
- Servlet基础(三) Servlet的多线程同步问题
- 【分块】bzoj3343: 教主的魔法
- nginx启动、重启、关闭
- 小议前端代码规范
- 接口
- IP头部协议字段
- 一致性哈希算法与Java实现
- iOS中UITextField详解
- 没有找到libmysql.dll,因此这个应用程序未能启动。重新安装应用程序可能会修复此问题
- 百度告警-Nagios接入
- navgicat for MySQL不联网不能连接MySQL