非递归遍历二叉树的前序中序后序

/**
     * 二叉树先序遍历,非递归算法
     * 1.申请一个新的栈,记为stack。然后将头节点head压入stack中。
     * 2.从stack弹出栈顶节点,记为cur,然后打印cur节点的值,再将cur右孩子(不为空)
     *   压入stack中,最后将cur的左孩子(不为空)压入stack中
     * 3.不断重复步骤2,直到stack为空,全部过程结束。
     * @param head
     */
    public void preOrderNoRecur(Node head){
        System.out.print("非递归前序遍历: ");
        if(head != null){
            Stack<Node> stack = new Stack<>();
            stack.push(head);
            while(!stack.isEmpty()){
                Node cur = stack.pop();
                System.out.print(cur.value + " ");
                if(cur.right != null){
                    stack.push(cur.right);
                }
                if(cur.left != null){
                    stack.push(cur.left);
                }
            }

        }
    }
 /**
     * 二叉树非递归中序遍历
     * 1.申请一个栈,记为stack。初始时,令cur = head。
     * 2.先把cur节点压入栈中,对以cur节点为头的整棵子树来说,依次把左边界压入栈中,
     *   即不停地令cur=cur.left,然后重复步骤2
     * 3.不断重复步骤2,直到发现cur为空,此时从stack中弹出一个节点,记为node。
     *   打印node的值,并且让cur=cur.right,然后重复步骤2.
     * 4.挡stack为空且cur为空时,整个过程停止。
     *
     * @param head
     */
    public void inOrderNoRecur(Node head){
        System.out.println("非递归中序遍历");
        if(head != null){
            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.print(head.value + " ");
                   head = head.right;
               }

            }

        }
    }
/**
     * 非递归后序遍历二叉树
     * 1.申请一个栈,记为s1,然后将头节点head压入s1中
     * 2.从s1中弹出的节点记为cur,然后依次将cur的左孩子和右孩子压入s1中。
     * 3.整个过程中,每一个从s1中弹出的节点都放入s2中
     * 4.不断重复步骤2和步骤3,直到s1为空,过程停止。
     * 5.从s2中依次弹出的节点并且打印,打印的顺序就是后序遍历的顺序。
     * @param head
     */
    public void postOrderNoRecur(Node head){
        System.out.println("非递归后序遍历二叉树");
        if(head != null){
            Stack<Node> stack1 = new Stack<>();
            Stack<Node> stack2 = new Stack<>();
            stack1.push(head);
            while(!stack1.isEmpty()){
                head = stack1.pop();
                if(head.left !=null){
                    stack1.push(head.left);
                }
                if(head.right != null){
                    stack1.push(head.right);
                }
                stack2.push(head);
            }

            while(!stack2.isEmpty()){
                System.out.print(stack2.pop().value + " ");
            }
        }
    }

 

posted @ 2016-10-30 15:55  huangyichun  阅读(278)  评论(0编辑  收藏  举报