每日一题力扣654

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

二叉树的根是数组 nums 中的最大元素。
左子树是通过数组中 最大值左边部分 递归构造出的最大二叉树。
右子树是通过数组中 最大值右边部分 递归构造出的最大二叉树。
返回有给定数组 nums 构建的 最大二叉树 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution:
    def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
        if not nums:#如果数组没有的话 就返回空
            return None
        maxv=max(nums)#找到数组中最大的数
        maxvi=nums.index(maxv)#找到数组中最大的数的下标
        root=TreeNode(maxv)#构建树
        root.left=self.constructMaximumBinaryTree(nums[:maxvi])#对最大的数左边的数进行如上操作
        root.right=self.constructMaximumBinaryTree(nums[maxvi+1:])#对最大的数右边的数进行如上操作
        return root
原文地址:https://www.cnblogs.com/liuxiangyan/p/14602064.html