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

二叉树 中很多问题都是通过遍历的方式来解决的,今天就来谢谢最常见的二叉树非递归遍历。

先定义一下节点的信息:

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);
		}
	}
}

    原文作者:方丈abbot
    原文地址: https://blog.csdn.net/wolf_fang/article/details/52699485
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞