【Leetcode_总结】654. 最大二叉树 - python

Q:

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

  1. 二叉树的根是数组中的最大元素。
  2. 左子树是通过数组中最大值左边部分构造出的最大二叉树。
  3. 右子树是通过数组中最大值右边部分构造出的最大二叉树。

通过给定的数组构建最大二叉树,并且输出这个树的根节点。

Example 1:

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

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1

链接:https://leetcode-cn.com/problems/maximum-binary-tree/description/

思路:数组和树考虑使用递归的方法,以数组中是否还有值为标准,递归构建最大二叉树

代码:

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        res = TreeNode(None)
        def d(root, nums):
            if not nums:
                return
            i = nums.index(max(nums))
            root.val = max(nums)
            if nums[:i]:
                root.left = TreeNode(None)
                d(root.left, nums[:i])
            if nums[i + 1:]:
                root.right = TreeNode(None)
                d(root.right, nums[i + 1:])
        d(res, nums)
        return res

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/85998695