【LeetCode】106. Construct Binary Tree from Inorder and Postorder Traversal 解題報告(Python)

題目分析:

根據一棵樹的中序遍歷與後序遍歷構造二叉樹。注意:你可以假設樹中沒有重複的元素。
例如,給出中序遍歷 inorder = [9,3,15,20,7],後序遍歷 postorder = [9,15,7,20,3]。返回如下的二叉樹:
在這裏插入圖片描述
解題思路:

這一題與105. Construct Binary Tree from Preorder and Inorder Traversal基本完全相同,可以參考上一個博客。

提交代碼1:(簡潔遞歸,時間複雜度O(N2),Runtime: 192 ms, faster than 40.77% )

class Solution:
    def buildTree(self, inorder: 'List[int]', postorder: 'List[int]') -> TreeNode:
        if not inorder:    return None
        root = TreeNode(postorder[-1])
        index = inorder.index(postorder[-1])
        root.left = self.buildTree(inorder[:index], postorder[:index])
        root.right = self.buildTree(inorder[index+1:], postorder[index:-1])
        return root

提交代碼2:(使用字典不必每次切割數組的遞歸,切片的時間複雜度是O(N),使時間複雜度下降到O(N),Runtime: 80 ms, faster than 79.52% )

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

參考博客

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