您的位置:首页 > 其它

二叉树 非递归 先序遍历 中序遍历 后序遍历 层次遍历

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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐