【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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]中给出了一段Java代码,是关于LeetCode 114题的解法。这道题的要求是将二叉树展开为一个单链表。引用\[2\]中提到了这道题可以用递归解法,而不一定要求空间复杂度为O(1)。引用\[3\]中给出了一种解题思路,即将子树插入到子树的地方,然后将原来的子树接到子树的最边节点,最后重复这个过程直到新的子树为null。 根据以上引用内容,可以使用递归的方式来解决LeetCode 114题。具体的Python代码如下: ```python class Solution: def flatten(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ if not root: return self.flatten(root.left) self.flatten(root.right) if root.left: temp = root.right root.right = root.left root.left = None while root.right: root = root.right root.right = temp ``` 这段代码首先判断根节点是否为空,如果为空则直接返回。然后递归地对子树子树进行展开。如果根节点的子树不为空,将子树保存到临时变量temp中,然后将子树赋值给子树子树置为空。接着,找到新的子树的最边节点,将temp连接到该节点的侧。 这样,通过递归的方式,就可以将二叉树展开为一个单链表。 #### 引用[.reference_title] - *1* *2* *3* [【LeetCode 114】二叉树展开为链表(Python)](https://blog.csdn.net/Lucy_R/article/details/107827298)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值