劍指offer學習(Java)——面試題7:重建二叉樹

題目:輸入某二叉樹的前序遍歷和中序遍歷結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。

牛客題目地址:重建二叉樹

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        if (pre == null || in == null || pre.length == 0 || in.length == 0) {
            return null;
        }
        return ConstructCore(pre, in, 0, pre.length-1, 0, in.length-1);
    }

    private TreeNode ConstructCore(int[] pre, int[] in, int startPre, int endPre, int startIn, int endIn) {
        int rootVal = pre[startPre];
        TreeNode root = new TreeNode(rootVal);
        if (startPre == endPre) {
            if (startIn == endIn && startPre == startIn) {
                return root;
            }
        }

        int rootIn = startIn;
        while (rootIn <= endIn && in[rootIn] != rootVal) {
            rootIn++;
        }

        int leftLength = rootIn - startIn;
        int leftEndPre = startPre + leftLength;
        if (leftLength > 0) {
            root.left = ConstructCore(pre, in, startPre + 1, leftEndPre, startIn, rootIn - 1);
        }
        if (leftLength < endPre - startPre) {
            root.right = ConstructCore(pre, in, leftEndPre + 1, endPre, rootIn + 1, endIn);
        }
        return root;
    }
}

做完題會引發一些思考,這裏題目中的假設“輸入的前序遍歷和中序遍歷的結果中都不含重複的數字”,是很關鍵的,不然在中序遍歷中就沒發確定根的位置了,也就無法重建二叉樹,

那麼由後序+中序來重建二叉樹也是類似的邏輯,代碼也只需簡單修改,

先序+後序 是無法重建二叉樹的,比如根是1、左子節點是2 和根是1、右子節點是2的兩個二叉樹的遍歷結果是相同的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章