日撸java 三百行 (day 14 )二叉树的中序遍历(栈)

今天是用非递归的方式遍历二叉树,需要借助一个辅助栈;

首先建立一个object类型的栈,并添加一个判定栈空的方法 isempty()。

package com.day07;

/**
 * Circle int queue.
 */
public class ObjectStack {
    /**
     * The depth.
     */
    public static final int MAX = 10;

    /**
     * The data
     */
    Object data[];

    /**
     * The actual depth.
     */
    int deep;

    /**
     * ********************
     * 构造一个空的栈
     * ********************
     */
    public ObjectStack() {
        data = new Object[MAX];
        deep = 0;
    }//of ObjectStack

    /**
     * ********************
     * Push an element.
     *
     * @param paraObject The given object.
     * @return Success or not.
     * ********************
     */
    public boolean push(Object paraObject) {
        if (deep == MAX) {
            return false;
        }//of if
        data[deep] = paraObject;
        deep++;
        return true;
    }//of push

    /**
     * ********************
     * Pop an element.
     *
     * @return The object at the top of the stack.
     * ********************
     */
    public Object pop() {
        if (deep == 0) {
            return null;
        }//of if
        deep--;
        return data[deep];
    }//of pop

    public void reset() {
        deep = 0;
    }//of reset

    /**
     * ********************
     * 重写toString方法
     * ********************
     */
    public String toString() {
        String resultString = "";
        for (int i = 0; i < deep; i++) {
            resultString += data[i];
        } // Of for i

        return resultString;


    }//of toString

    /**
     * ********************
     * Is the stack empty?
     *
     * @return True if empty.
     * ********************
     */
    public boolean isempty() {
        if (deep == 0) {
            return true;
        }//of if 
        return false;
    }//of isempty
}//of ObjectStack

以非递归的方式使用栈来进行遍历:

/**
     * ********************
     * 中序遍历(栈)
     * ********************
     */
    public void inOrderVisitWithStack() {
        ObjectStack tempStack = new ObjectStack();
        BinaryCharTree tempnodes = this;
        while (!tempStack.isempty() || tempnodes != null) {
            if (tempnodes != null) {
                tempStack.push(tempnodes);
                tempnodes = tempnodes.leftChild;
            } else {
                tempnodes = (BinaryCharTree) tempStack.pop();
                System.out.print("" + tempnodes.value + " ");
                tempnodes = tempnodes.rightChild;
            }
        }
    }

测试一下:


    /**
     * ********************
     * The entrance of the program.
     *
     * @param args Not used now.
     *             ********************
     */
    public static void main(String args[]) {
        BinaryCharTree tempTree = manualConstructTree();
        System.out.println("\r\nPreorder visit:");
        tempTree.preOrderVisit();
        System.out.println("\r\nIn-order visit:");
        tempTree.inOrderVisit();
        System.out.println("\r\nPost-order visit:");
        tempTree.postOrderVisit();

        System.out.println("\r\n\r\nThe depth is: " + tempTree.getDepth());
        System.out.println("The number of nodes is: " + tempTree.getNumNodes());

        tempTree.toDataArrays();
        System.out.println("The values are: " + Arrays.toString(tempTree.valuesArray));
        System.out.println("The indices are: " + Arrays.toString(tempTree.indicesArray));
        char[] tempCharArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
        int[] tempIndicesArray = {0, 1, 2, 4, 5, 9, 10};
        char[] tempCharArrayV2 = {'A', 'B', 'C', 'D', 'E', 'F'};
        int[] tempIndicesArrayV2 = {0, 1, 2, 4, 5, 12};
        BinaryCharTree tempTree2 = new BinaryCharTree(tempCharArray, tempIndicesArray);
        BinaryCharTree tempTree3 = new BinaryCharTree(tempCharArrayV2, tempIndicesArrayV2);
        System.out.println("\r\nPreorder visit:");
        tempTree2.preOrderVisit();
        System.out.println("\r\nIn-order visit:");
        tempTree2.inOrderVisit();
        System.out.println("\r\nPost-order visit:");
        tempTree2.postOrderVisit();
        System.out.println("\r\nIn-order visit with stack:");
        tempTree.inOrderVisitWithStack();
        System.out.println("\r\nIn-order visit with stack:");
        tempTree3.inOrderVisitWithStack();

    }// Of main

运行效果:

日撸java 三百行 (day 14 )二叉树的中序遍历(栈)_第1张图片

总结:这种方式遍历相比于递归仿佛是以人的思考模式走一遍中序遍历的流程,好处就是没有递归那么饶,难点就在于能不能想到用辅助栈,我就想为要啥用栈?理由是啥?为了搞清楚这个问题,我尝试一下不用栈,就硬写,看看会卡在什么地方;果然在某个地方卡住。总结下来就是:计算机没有记忆,当我遍历到叶子节点时需要往回走,哎嘿不知道走过哪些地方,这个时候就发现,原来栈就是来帮我记路的,然后联系到栈的特性后进先出,这不就是个妥妥的记事本。以后在解决回退问题时就可以试试栈了,算是个小收获。

你可能感兴趣的:(java,数据结构)