面试算法--递归/循环实现二叉树的前丶中丶后序遍历

一丶利用二叉树前序顺序构建二叉树

"#" 代表空结点

/**
     * 
     *               A
     * 
     *          B           C
     * 
     *      D       E     #         F 
     * 
     *    #   #   #   #           #    #
     * 
     * 
     * A B D## E## C # F ## 利用前序遍历快速反向创建二叉树
     */
    public void createBinaryTreePre(ArrayList<String> data) {

        createBinaryTree(data);
    }

    private Node createBinaryTree(ArrayList<String> data) {

        if (0 == data.size()) {
            return null;
        }

        String d = data.get(0);

        if ("#".equals(d)) {
            data.remove(0);
            return null;
        }

        Node node = new Node(0, d);
        data.remove(0);

        if (null == root) {
            root = node;
        }

        node.leftChild = createBinaryTree(data);

        node.rightChild = createBinaryTree(data);

        return node;
    }

二丶递归实现二叉树前中后序遍历

/**
     * 递归方式实现前序遍历
     */
    public void recursionPrerEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 先输出根节点
        System.out.println("数据:" + node.data);

        // 输出左边节点 根节点左边的可以看成是一个子树,递归调用此方法即可
        recursionPrerEgodic(node.leftChild);

        // 输出右边节点
        recursionPrerEgodic(node.rightChild);
    }

    /**
     * 递归方式实现中序遍历
     */
    public void recursionMidEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 先递归输出左边的节点
        recursionMidEgodic(node.leftChild);

        // 先输出根节点
        System.out.println("数据:" + node.data);

        // 最后输出右边节点
        recursionMidEgodic(node.rightChild);
    }

        /**
     * 递归方式实现后序遍历
     */
    public void recursionPostEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 先递归输出左边的节点
        recursionPostEgodic(node.leftChild);

        // 最后输出右边节点
        recursionPostEgodic(node.rightChild);

        // 先输出根节点
        System.out.println("数据:" + node.data);
    }

三丶循环实现二叉树前中后序遍历

/**
     * 循环方式实现前序遍历 借助栈实现
     */
    public void loopPreEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 借用栈实现
        Stack<Node> stack = new Stack<Node>();

        stack.push(node);

        while (!stack.isEmpty()) {

            // 从栈中取出数据。
            node = stack.pop();

            // 取出数据
            System.out.println("数据:" + node.data);

            // 因为是跟 左 右 而栈是先进后出,所以一定要先把右边压入栈中 再压入左面,

            // 如果此节点左右节点不为null,将此节点的左右节点压入栈中

            if (null != node.rightChild) {

                stack.push(node.rightChild);
            }

            if (null != node.leftChild) {

                stack.push(node.leftChild);
            }
        }
    }

    /**
     * 循环方式实现中序遍历 借用栈实现
     */
    public void loopMidEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 借用栈实现
        Stack<Node> stack = new Stack<Node>();

        while (!stack.isEmpty() || null != node) {

            // 先遍历出所有左节点放入栈中,停止条件是node指针为null
            if (null != node) {

                stack.push(node);

                // node指针指向左节点
                node = node.leftChild;

            } else {

                // 此时取出栈中的数据
                node = stack.pop();

                System.out.println("数据:" + node.data);

                node = node.rightChild;
            }
        }
    }

    /**
     * 循环方式实现后序遍历方法一 借用双栈实现
     */
    public void loopPostEgodic_1(Node node) {

        if (null == node) {
            return;
        }

        // 借用双栈实现
        Stack<Node> s1 = new Stack<Node>();
        Stack<Node> s2 = new Stack<Node>();

        s1.push(node);

        while (!s1.isEmpty()) {

            node = s1.pop();

            // 先不输出,先将根节点压入栈2,最后输出
            s2.push(node);

            // 注意 以下代码顺序不能换
            // 放入栈1后 左在栈底 右 在栈顶,放入栈2后,左在栈顶,右在栈底 ,而根节点早就放在栈2底部了,
            if (null != node.leftChild) {

                s1.push(node.leftChild);
            }

            if (null != node.rightChild) {

                s1.push(node.rightChild);
            }
        }

        while (!s2.isEmpty()) {
            node = s2.pop();
            System.out.println("数据:" + node.data);
        }
    }

    /**
     * 循环方式实现后序遍历方法二
     */
    public void loopPostEgodic_2(Node node) {

        if (null == node) {

            return;
        }

        Stack<Node> stack = new Stack<Node>();

        stack.push(node);

        Node pre = null;

        while (!stack.isEmpty()) {

            pre = stack.peek();// 注意只取出不移除

            if (pre.leftChild != null && node != pre.leftChild && node != pre.rightChild) {

                stack.push(pre.leftChild);
            }

            else if (pre.rightChild != null && node != pre.rightChild) {

                stack.push(pre.rightChild);
            }

            else {
                node = stack.pop();
                System.out.println("数据:" + node.data);
                node = pre;
            }
        }
    }

四丶完整代码

public class WDBinaryTree {

    class Node {
        int index;
        String data;

        Node parent;
        Node leftChild;
        Node rightChild;

        public Node(int index, String data) {
            super();
            this.data = data;
            this.index = index;

            this.parent = null;
            this.leftChild = null;
            this.rightChild = null;
        }
    }

    Node root = null;

    /**
     * 
     *               A
     * 
     *          B           C
     * 
     *      D       E     #         F 
     * 
     *    #   #   #   #           #    #
     * 
     * 
     * A B D## E## C # F ## 利用前序遍历快速反向创建二叉树
     */
    public void createBinaryTreePre(ArrayList<String> data) {

        createBinaryTree(data);
    }

    private Node createBinaryTree(ArrayList<String> data) {

        if (0 == data.size()) {
            return null;
        }

        String d = data.get(0);

        if ("#".equals(d)) {
            data.remove(0);
            return null;
        }

        Node node = new Node(0, d);
        data.remove(0);

        if (null == root) {
            root = node;
        }

        node.leftChild = createBinaryTree(data);

        node.rightChild = createBinaryTree(data);

        return node;
    }

    /**
     * 获取二叉树的高度
     */
    public int getHeight(Node node) {

        if (null == node) {
            return 0;
        }

        int i = getHeight(node.leftChild);

        int j = getHeight(node.rightChild);

        return i > j ? (i + 1) : (j + 1);
    }

    /**
     * 获取二叉树的节点数
     */
    public int getNum(Node node) {

        if (null == node) {
            return 0;
        }

        return 1 + getNum(node.leftChild) + getNum(node.rightChild);
    }

    /**
     * 递归方式实现前序遍历
     */
    public void recursionPrerEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 先输出根节点
        System.out.println("数据:" + node.data);

        // 输出左边节点 根节点左边的可以看成是一个子树,递归调用此方法即可
        recursionPrerEgodic(node.leftChild);

        // 输出右边节点
        recursionPrerEgodic(node.rightChild);
    }

    /**
     * 递归方式实现中序遍历
     */
    public void recursionMidEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 先递归输出左边的节点
        recursionMidEgodic(node.leftChild);

        // 先输出根节点
        System.out.println("数据:" + node.data);

        // 最后输出右边节点
        recursionMidEgodic(node.rightChild);
    }

    /**
     * 递归方式实现后序遍历
     */
    public void recursionPostEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 先递归输出左边的节点
        recursionPostEgodic(node.leftChild);

        // 最后输出右边节点
        recursionPostEgodic(node.rightChild);

        // 先输出根节点
        System.out.println("数据:" + node.data);
    }

    /**
     * 循环方式实现前序遍历 借助栈实现
     */
    public void loopPreEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 借用栈实现
        Stack<Node> stack = new Stack<Node>();

        stack.push(node);

        while (!stack.isEmpty()) {

            // 从栈中取出数据。
            node = stack.pop();

            // 取出数据
            System.out.println("数据:" + node.data);

            // 因为是跟 左 右 而栈是先进后出,所以一定要先把右边压入栈中 再压入左面,

            // 如果此节点左右节点不为null,将此节点的左右节点压入栈中

            if (null != node.rightChild) {

                stack.push(node.rightChild);
            }

            if (null != node.leftChild) {

                stack.push(node.leftChild);
            }
        }
    }

    /**
     * 循环方式实现中序遍历 借用栈实现
     */
    public void loopMidEgodic(Node node) {

        if (null == node) {
            return;
        }

        // 借用栈实现
        Stack<Node> stack = new Stack<Node>();

        while (!stack.isEmpty() || null != node) {

            // 先遍历出所有左节点放入栈中,停止条件是node指针为null
            if (null != node) {

                stack.push(node);

                // node指针指向左节点
                node = node.leftChild;

            } else {

                // 此时取出栈中的数据
                node = stack.pop();

                System.out.println("数据:" + node.data);

                node = node.rightChild;
            }
        }
    }

    /**
     * 循环方式实现后序遍历方法一 借用双栈实现
     */
    public void loopPostEgodic_1(Node node) {

        if (null == node) {
            return;
        }

        // 借用双栈实现
        Stack<Node> s1 = new Stack<Node>();
        Stack<Node> s2 = new Stack<Node>();

        s1.push(node);

        while (!s1.isEmpty()) {

            node = s1.pop();

            // 先不输出,先将根节点压入栈2,最后输出
            s2.push(node);

            // 注意 以下代码顺序不能换
            // 放入栈1后 左在栈底 右 在栈顶,放入栈2后,左在栈顶,右在栈底 ,而根节点早就放在栈2底部了,
            if (null != node.leftChild) {

                s1.push(node.leftChild);
            }

            if (null != node.rightChild) {

                s1.push(node.rightChild);
            }
        }

        while (!s2.isEmpty()) {
            node = s2.pop();
            System.out.println("数据:" + node.data);
        }
    }

    /**
     * 循环方式实现后序遍历方法二
     */
    public void loopPostEgodic_2(Node node) {

        if (null == node) {

            return;
        }

        Stack<Node> stack = new Stack<Node>();

        stack.push(node);

        Node pre = null;

        while (!stack.isEmpty()) {

            pre = stack.peek();// 注意只取出不移除

            if (pre.leftChild != null && node != pre.leftChild && node != pre.rightChild) {

                stack.push(pre.leftChild);
            }

            else if (pre.rightChild != null && node != pre.rightChild) {

                stack.push(pre.rightChild);
            }

            else {
                node = stack.pop();
                System.out.println("数据:" + node.data);
                node = pre;
            }
        }
    }

    /**
     * 层序 利用队列实现
     */
    public void levelEgodic(Node node) {

        if (null == node) {
            return;
        }

        Queue<Node> q = new LinkedList<Node>();
        q.add(node);

        while (!q.isEmpty()) {

            //源码: Retrieves and removes the head of this queue,
            node = q.poll();// 取出并移除

            System.out.println("数据:" + node.data);

            if (null != node.leftChild) {
                q.add(node.leftChild);
            }
            if (null != node.rightChild) {
                q.add(node.rightChild);
            }
        }
    }

    public static void main(String[] args) {

        //二叉树的前序遍历顺序,#代表空结点
        String[] data = { "A", "B", "D", "#", "#", "E", "#", "#", "C", "#", "F", "#", "#" };

        ArrayList<String> dataList = new ArrayList<String>();

        for (String s : data) {
            dataList.add(s);
        }

        //构造二叉树
        WDBinaryTree tree = new WDBinaryTree();
        tree.createBinaryTreePre(dataList);

        int i = tree.getHeight(tree.root);
        int num = tree.getNum(tree.root);

        System.out.println("二叉树的高度为:" + i);
        System.out.println("二叉树的节点数为:" + num);

        System.out.println("递归实现--");

        System.out.println("前序:");
        tree.recursionPrerEgodic(tree.root);

        System.out.println("中序:");
        tree.recursionMidEgodic(tree.root);

        System.out.println("后序:");
        tree.recursionPostEgodic(tree.root);

        // 递归调用一个方法,相当于将数据加入一个栈中,先进后出

        System.out.println("循环实现--");

        System.out.println("前序:");
        tree.loopPreEgodic(tree.root);

        System.out.println("中序:");
        tree.loopMidEgodic(tree.root);

        System.out.println("后序1:");
        tree.loopPostEgodic_1(tree.root);

        System.out.println("后序2:");
        tree.loopPostEgodic_2(tree.root);

        System.out.println("层序:");
        tree.levelEgodic(tree.root);
    }
}

五丶测试结果

图片.png
图片.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容