面试准备--二叉树的非递归遍历(Java版)
2016-09-19 19:55
239 查看
函数是写在树类中.
前序和中序都是差不多,不过在于输出的顺序而已.
1. 前序在遍历最左节点时,边遍历边输出.
2. 中序在取出栈顶元素和放入右子树之间时输出.
后序遍历比较麻烦,要保证左右子树必须在根节点之前遍历输出.遍历根节点的条件:无左右子树或者已经遍历了左右子树(遍历的前一个节点就是左右子树).右子树先进栈,这样在出栈的时候就是左子树先出栈.
前序和中序都是差不多,不过在于输出的顺序而已.
1. 前序在遍历最左节点时,边遍历边输出.
2. 中序在取出栈顶元素和放入右子树之间时输出.
//中序非递归遍历二叉树 public ArrayList<Integer> zsort(){ Stack<Node> s = new Stack<Node>(); ArrayList<Integer> q = new ArrayList<Integer>(); Node p; s.add(root); while(!s.empty()){ p = s.peek(); while(p!=null){ s.push(p.getLeft()); p = p.getLeft(); } s.pop(); if(!s.empty()){ p = s.pop(); q.add(p.getData()); s.push(p.getRight()); } } return q; }
//非递归前序遍历二叉树 public ArrayList<Integer> qsort(){ Stack<Node> s = new Stack<Node>(); ArrayList<Integer> q = new ArrayList<Integer>(); Node p; s.push(root); while(!s.empty()){ p = s.peek(); while(p!=null){ q.add(p.getData()); s.push(p.getLeft()); p = p.getLeft(); } s.pop(); if(!s.empty()){ p = s.pop(); s.push(p.getRight()); } } return q; }
后序遍历比较麻烦,要保证左右子树必须在根节点之前遍历输出.遍历根节点的条件:无左右子树或者已经遍历了左右子树(遍历的前一个节点就是左右子树).右子树先进栈,这样在出栈的时候就是左子树先出栈.
//非递归后序遍历二叉树 public ArrayList<Integer> hsort(){ Stack<Node> s = new Stack<Node>(); ArrayList<Integer> q = new ArrayList<Integer>(); Node now = null; Node pre = null; s.push(root); while(!s.empty()){ now = s.peek(); if((now.getLeft() == null && now.getRight() == null) || (pre != null &&( pre == now.getLeft() || pre == now.getRight() ) ) ){ q.add(now.getData()); s.pop(); pre = now; } else { if(now.getRight()!=null){ s.push(now.getRight()); } if(now.getLeft()!=null){ s.push(now.getLeft()); } } } return q; }
相关文章推荐
- 我的Java工程师面试之准备
- 二叉树的递归与非递归遍历(Java描述)
- 【java失业择业中】失业第四天:准备面试
- java集群技术面试的一些知识准备
- java面试前本人需准备的内容
- Java面试要准备的问题
- java面试准备之基础排序——冒泡与选择排序
- 【java失业择业中】失业第三天:准备面试
- 【java失业择业中】失业第二天:准备面试
- java api 视频面试准备
- 二叉树的递归与非递归遍历(Java描述)
- java面试准备之---Struts2体系知识点,系统复习,struts2原理,ognl,el支持.---随时更新
- [面试] 根据前序和中序重建二叉树,并且中序非递归遍历
- 【java失业择业中】失业第三天:准备面试
- 准备Java面试一个月,倒计时之Java基础01
- java程序员面试如何准备
- [面试] 根据前序和中序重建二叉树,并且中序非递归遍历
- java面试准备---JSF系统学习知识点总结---随时更新
- 【java失业择业中】失业第四天:准备面试
- java实现二叉树的非递归遍历