【leetcode-106】從後序與中序遍歷序列構造二叉樹

根據一棵樹的中序遍歷與後序遍歷構造二叉樹

例如,給出

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

返回如下的二叉樹:

​ 3
/\
9 20
​ / \
15 7

來源:leetcode - 106

知識點:

  • 後序遍歷:[ [ 左子樹的前序遍歷結果 ],[ 右子樹的前序遍歷結果 ],根節點]
  • 中序遍歷:[[ 左子樹的遍歷結果 ],根節點,[ 右子樹的中序遍歷結果 ]]

簡要思路:先根據後序遍歷的概念,找出根節點,再在中序遍歷中根據找到的根節點找出其左子樹和右子樹。

詳細思路:後序遍歷結果中最後一個元素就是根節點,找出根節點後,再在中序遍歷中找出根節點的位置,依靠根節點的位置將中序遍歷劃分開來,構造根節點,繼續遞歸左子樹和右子樹進行構造,最終構造完整棵樹,其中,爲了減小時間複雜度,我們將中序遍歷數組用 HashMap 存儲起來,每次要在中序遍歷結果中找根節點的位置時,只需要查找 HashMap 就可,降低了時間複雜度。

代碼:

class Solution {
    private Map<Integer, Integer> indexMap;

    public TreeNode myBuildTree(int[] inorder, int inorder_left, int inorder_right, int[] postorder, int postorder_left, int postorder_right){
        if(inorder_left > inorder_right || postorder_left > postorder_right){
            return null;
        }
        // 後序遍歷根節點的位置
        int postorder_root = postorder_right;
        // 中序遍歷根節點的位置
        int inorder_root = indexMap.get(postorder[postorder_root]);
        // 得到左子樹節點的個數
        int size_left_subtree = inorder_root - inorder_left;
        // 構建根節點
        TreeNode root = new TreeNode(postorder[postorder_root]);
        // 構建左子樹
        root.left = myBuildTree(inorder, inorder_left, inorder_root - 1, postorder, postorder_left, postorder_left + size_left_subtree - 1);
        root.right = myBuildTree(inorder, inorder_root + 1, inorder_right, postorder, postorder_left + size_left_subtree, postorder_right - 1);
        return root;

    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        int n = postorder.length;
        indexMap = new HashMap<Integer, Integer>();
        for (int i=0; i<n; i++){
            indexMap.put(inorder[i], i);
        }
        return myBuildTree(inorder, 0, n-1, postorder,0, n-1);
    }
}

這一題與 leetcode - 105 簡直一摸一樣,你品,你細品 (手動狗頭)

參考資料:官方題解

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