654. 最大二叉树

给定一个不含重复元素的整数数组。一个以此数组构建的最大二叉树定义如下:

二叉树的根是数组中的最大元素。

  1. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
  2. 右子树是通过数组中最大值右边部分构造出的最大二叉树。
  3. 通过给定的数组构建最大二叉树,并且输出这个树的根节点。

Example 1:

输入: [3,2,1,6,0,5]
输入: 返回下面这棵树的根节点:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

注意:

  • 给定的数组的大小在 [1, 1000] 之间。

思路:

  • 当数组为空时,返回None
  • 否则计算数组最大的数,并且得到其下标,然后递归对左边数组和右边数组进行最大数构建即可。
class Solution:
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None

        max_num = max(nums)

        max_index = nums.index(max_num)

        left_nums = nums[:max_index]
        right_nums = nums[max_index+1:]

        root = TreeNode(max_num)
        root.left = self.constructMaximumBinaryTree(left_nums)
        root.right = self.constructMaximumBinaryTree(right_nums)

        return root
posted @ 2018-09-20 14:01  yuyin  阅读(162)  评论(0编辑  收藏  举报