算法練習每日一題:最大二叉樹【Python】

654. 最大二叉樹

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

二叉樹的根是數組中的最大元素。
左子樹是通過數組中最大值左邊部分構造出的最大二叉樹。
右子樹是通過數組中最大值右邊部分構造出的最大二叉樹。

通過給定的數組構建最大二叉樹,並且輸出這個樹的根節點。

示例 :

輸入:[3,2,1,6,0,5]
輸出:返回下面這棵樹的根節點:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

提示:

給定的數組的大小在 [1, 1000] 之間。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/maximum-binary-tree

"""遞歸方式求解
# Testcase:

>>> Solution().test([3,2,1,6,0,5])
[6,3,5,null,2,0,null,null,1]

"""

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
#     def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
    def constructMaximumBinaryTree(self, nums):
        if not nums:
            return
        max_num = max(nums)
        max_index = nums.index(max_num)
        root = TreeNode(max_num)
        root.left = self.constructMaximumBinaryTree(nums[:max_index])
        root.right = self.constructMaximumBinaryTree(nums[max_index+1:])
        return root
    
    def test(self, nums):
        root = self.constructMaximumBinaryTree(nums)
        print(self.constructMaximumBinaryTree(nums))
if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True)
           
Trying:
    Solution().test([3,2,1,6,0,5])
Expecting:
    [6,3,5,null,2,0,null,null,1]
**********************************************************************
File "__main__", line 5, in __main__
Failed example:
    Solution().test([3,2,1,6,0,5])
Expected:
    [6,3,5,null,2,0,null,null,1]
Got:
    6
5 items had no tests:
    __main__.Solution
    __main__.Solution.constructMaximumBinaryTree
    __main__.Solution.test
    __main__.TreeNode
    __main__.TreeNode.__init__
**********************************************************************
1 items had failures:
   1 of   1 in __main__
1 tests in 6 items.
0 passed and 1 failed.
***Test Failed*** 1 failures.

題解

要仔細讀清楚要求,先找出最大值,然後 left 爲左半部分的最大值,right 爲其有半部分的最大值;遞歸求解便於理解。

這裏有 max_num 標籤,分治思想。也可以使用隊列和迭代方式。

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