zoukankan      html  css  js  c++  java
  • 非递归方式遍历二叉树

      /**
         * 非递归方式的先根序
         * @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;
    	}
    
    }
    

      

  • 相关阅读:
    装饰者模式
    NGUI研究院之三种方式监听NGUI的事件方法(七)
    unity3d连接数据库
    unity3d 连接MSSql
    Unity3D之游戏架构脚本该如何来写
    WCF 部署问题 小总结 (HTTP 不能注册的解决方法)
    Prototype
    web.config文件之自定义错误节
    asp:DropDownList与asp:DataList的联合使用
    剑指offer --合并链表
  • 原文地址:https://www.cnblogs.com/wangxiaowang/p/7818796.html
Copyright © 2011-2022 走看看