【劍指offer】7.重建二叉樹

7.重建二叉樹

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

例如,給出

前序遍歷 preorder = [3,9,20,15,7]

中序遍歷 inorder = [9,3,15,20,7]

返回如下的二叉樹:

3

/ \

9 20

/  \

15 7

th:前序遍歷第一個數就是root節點,而我們用map記錄中序順序,用根節點區分左右節點 遞歸調用。

time : O(n)

space : O(n)

   static Map<Integer,Integer> result = new HashMap<>();
    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        for(int i=0;i<inorder.length;i++){
            result.put(inorder[i],i);
        }
        return recur(preorder,0,preorder.length-1,0);
    }

    public static TreeNode recur(int [] pre,int preL,int preR,int inL){
        if(preL > preR){
            return null;
        }
        TreeNode root = new TreeNode(pre[preL]);
        int rootIndex = result.get(root.val);
        int size = rootIndex - inL;
        root.left = recur(pre,preL+1,preL+size,inL);
        root.right = recur(pre,preL+1+size,preR,inL+size+1);
        return root;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章