654. Maximum Binary Tree——tree

题目分析:

思路一:采用递归,分为三步,分别为获取指定数组序列的最大值,构建子树,返回根节点。

获取指定数组最大值findmax函数(Python自带max函数):参数为数组nums,起始位置start,终止位置end,最大值max。求出数组中,指定了起始位置和终止位置后的最大值,并返回最大值所在数组的下标index,如果起始位置等于终止位置,返回index=-1。

构建子树getsubtree函数:参数为数组nums,起始位置start,终止位置end。定义最大值max,调用findmax函数,定义并初始化index为数组nums从0到数组结尾中最大值的下面。如果index为-1,说明此时搜寻的数组为空,则返回null节点。否则,创建val值为max的节点node,递归调用getsubtree函数,得到其左右节点。其左节点为getsubtree(nums, start, index),右节点为getsubtree(nums, index + 1, end),注意nums的起始与终止位置。最后返回node节点。

返回根节点constructMaximumBinaryTree函数:返回调用getsubtree(nums, 0, nums.size())函数的结果。
 

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

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        def getsubtree(nums,start,end):
            if start==end:
                return None
            max_=max(nums[start:end])
            node=TreeNode(max_)
            node.left=getsubtree(nums,start,nums.index(max_))
            node.right=getsubtree(nums, nums.index(max_)+1, end)
            return node

        return getsubtree(nums, 0, len(nums))

 

 

class Solution2(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None
        node=TreeNode(max(nums))
        i=nums.index(max(nums))
        if nums[:i]:
            node.left=self.constructMaximumBinaryTree(nums[:i])
        if nums[i+1:]:
            node.right=self.constructMaximumBinaryTree(nums[i+1:])
        return node
--------------------- 
 

相关文章:

  • 2021-04-12
  • 2021-10-09
  • 2022-12-23
  • 2021-05-22
  • 2021-05-07
  • 2021-12-30
  • 2022-12-23
  • 2021-09-03
猜你喜欢
  • 2021-12-23
  • 2021-07-05
  • 2021-09-24
  • 2021-09-21
  • 2021-12-10
  • 2022-12-23
  • 2022-01-21
相关资源
相似解决方案