二叉树 非递归 先序遍历 中序遍历 后序遍历 层次遍历
2016-09-29 10:25
429 查看
二叉树 中很多问题都是通过遍历的方式来解决的,今天就来谢谢最常见的二叉树非递归遍历。
先定义一下节点的信息:
先定义一下节点的信息:
class TreeNode{ public int value; public TreeNode left; public TreeNode right; public TreeNode(int value){ this.value = value; } }
1. 先序 非递归 遍历
//先序非递归遍历 public void preOrderUnRecur(TreeNode node){ if(node==null){ return; } Stack<TreeNode> stack = new Stack<>(); stack.add(node); while(!stack.isEmpty()){ System.out.println(node.value); if(node.right!=null){ stack.add(node.left); } if(node.left!=null){ stack.add(node.right); } } }
2. 中序 非递归 遍历
public void inOrderUnRecur(TreeNode head){ if(null==head){ return; } Stack<Node> stack = new Stack<>(); while(!stack.isEmpty() || head!=null){ if(head!=null){ stack.push(head); head = head.left; }else{ head = stack.pop(); System.out.println(head.value); head = head.right; } } }
3. 后序 非递归 遍历
public void posOrderUnRecur(TreeNode h){ if(h==null){ return; } Stack<TreeNode> stack = new Stack<>(); stack.push(h); TreeNode c = null; while(!stack.isEmpty()){ c = stack.peek(); if(c.left!=null && h!=c.left && h!=c.right){ stack.push(c.left); }else if(c.right!=null && h!=c.right){ stack.push(c.right); }else{ System.out.print(stack.pop().value+" "); h = c; } } }
4. 层序遍历
public void layerTran(TreeNode root){ if(root==null){ return; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while(!queue.isEmpty()){ TreeNode c = queue.poll(); System.out.println(c.value); if(c.left!=null){ queue.add(c.left); } if(c.right!=null){ queue.add(c.right); } } }
相关文章推荐
- 二叉树中结构体的应用,以及先序,中序,后序,层次遍历的输出
- 二叉树各种相关操作(建立二叉树、前序、中序、后序、求二叉树的深度、查找二叉树节点,层次遍历二叉树等)(C语言版)
- 二叉树的先序,中序,后序,层次,递归,非递归遍历
- 层次创建二叉树及后序遍历
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 二叉树的前中后层次遍历(递归+非递归)、创建树(数组、前序+中序、中序加后序)
- 采用二叉链表结构实现二叉树,并以递归遍历思想实现二叉树的创建、二叉树的遍历(先序、中序、后序和层次遍历)
- 二叉树的创建,前、中、后序遍历以及层次遍历
- 树之二叉树的建立与四种遍历(前序,中序, 后序, 层次)及树的深度
- 二叉树的建树、遍历(先序、中序、后序、层次)(递归和非递归)--Java实现
- LintCode 二叉树的前序,中序,后序,层次遍历
- java语言实现二叉树的前序、中序与后序遍历(递归与非递归) 层次遍历
- 数据结构:题目(4)遍历二叉树的四种方法: 依次是:层次、前序、中序、后序
- Java二叉树(一)--定义及前序、中序、后序、层次遍历及求高度的实现
- 二叉树的先序遍历、中序遍历、后序遍历、层次遍历的递归实现
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- java 实现二叉树的构建,先序,中序,后序,层次,递归,非递归的遍历
- 树之二叉树的建立与四种遍历(前序,中序, 后序, 层次)及树的深度
- 二叉树的创建、二叉排序树、前序、中序、后序、层次遍历
- 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现