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
--------------------- 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值