【力扣】654:最大二叉樹 | 遞歸

題目描述

給定一個不含重複元素的整數數組。一個以此數組構建的最大二叉樹定義如下:

二叉樹的根是數組中的最大元素。
左子樹是通過數組中最大值左邊部分構造出的最大二叉樹。
右子樹是通過數組中最大值右邊部分構造出的最大二叉樹。
通過給定的數組構建最大二叉樹,並且輸出這個樹的根節點。

算法思路

其實類似【力扣日記】面試題04.02:最小高度樹 |遞歸

偷了個懶,暴力求最大值

class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
        if not nums:return 
        a,b=0,0
        for i,j in enumerate(nums):
            if j>a:
                a,b=j,i
        
        r=TreeNode(a)
        r.left=self.constructMaximumBinaryTree(nums[:b])
        r.right=self.constructMaximumBinaryTree(nums[b+1:])
        return r

執行用時 :248 ms, 在所有 Python3 提交中擊敗了44.98%的用戶
內存消耗 :13.9 MB, 在所有 Python3 提交中擊敗了20.00%的用戶

內置方法都沒用習慣可是丟臉了啊

class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
        if len(nums)<1:return 
        idx = nums.index(max(nums))
        root = TreeNode(nums[idx])
        root.left = self.constructMaximumBinaryTree(nums[:idx])
        root.right = self.constructMaximumBinaryTree(nums[idx+1:])
        return root
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章