非递归方式遍历二叉树

  /**
     * 非递归方式的先根序
     * @param root
     */
    public static void preOrder(Node root){
        Stack<Node> stack = new Stack<Node>();
        while (!stack.isEmpty() || root != null) {
        	while (root != null) {
        		System.out.println(root.data);
        		stack.push(root);
        		root = root.left;
        	}
        	
        	if (!stack.isEmpty()) {
        		root = stack.pop();
        		root = root.right;
        	}
        }
        
    }
    
    /**
     * 非递归的方式中根序遍历二叉树
     * @param node
     */
    public static void orderBinaryTree(Node node) {
    	Stack<Node> stack = new Stack<Node>();
    	Node point = node;
    	while (!stack.isEmpty() || point != null) {
    		//如果左子树不为空,则一直入栈
    		if (point != null) {
    			stack.push(point);
    			point = point.left;
    		} else {
    			point = stack.peek();
    			visit(point);
    			point = point.right;
    			stack.pop();
    		}
    	}
    }
    
    /**
     * 非递归方式后根序
     * @param node
     */
    public static void lastOrder(Node node) {
    	Stack<Node> stackNode = new Stack<Node>();
    	Stack<Integer> stackInt = new Stack<Integer>();
    	int i = 1;
    	while (!stackNode.isEmpty() || node != null) {
    		while(node != null) {
    			stackNode.push(node);
    			stackInt.push(0);
    			node = node.left;
    		}
    		while (!stackNode.isEmpty() && stackInt.peek() == i) {
    			stackInt.pop();
    			System.out.println(stackNode.pop().data);
    		}
    		
    		if (!stackNode.isEmpty()) {
    			stackInt.pop();
    			stackInt.push(1);
    			node = stackNode.peek();
    			node = node.right;
    		}
    	}
    }
    

  创建一棵二叉树:

public class Node {
	Node left = null;
	Node right = null;
	Integer data;
	/**
	 * 
	 * @param root
	 */
	public Node() {
		this.left = null;
		this.right = null;
		this.data = null;
	}
	
	public Node(Integer data) {
		this.left = null;
		this.right= null;
		this.data = data;
	}

}

  

转载于:https://www.cnblogs.com/wangxiaowang/p/7818796.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值