算法练习每日一题:最大二叉树【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 标签,分治思想。也可以使用队列和迭代方式。

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