1. 程式人生 > 實用技巧 >LeetCode #106. Construct Binary Tree from Inorder and Postorder Traversal

LeetCode #106. Construct Binary Tree from Inorder and Postorder Traversal

題目

106. Construct Binary Tree from Inorder and Postorder Traversal


解題方法

這道題與105. Construct Binary Tree from Preorder and Inorder Traversal的區別在於給的條件不同,之前給的是先序遍歷和中序遍歷,這次給的是中序遍歷和後序遍歷,但解決問題的思路類似,都是先通過前序和後序遍歷確定根在中序的位置,再將其一分為二分別遞迴。

值得注意的是,面試中建議採用字典的方法來減少大量的計算時間。


程式碼

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        map_inorder = {}
        for i, val in enumerate(inorder):
            map_inorder[val] = i
        
        def recur(low, high):
            if low > high:
                return None
            x = TreeNode(postorder.pop())
            mid = map_inorder[x.val]
            x.right = recur(mid + 1, high)
            x.left = recur(low, mid - 1)
            return x
        
        return recur(0, len(inorder) - 1)