leetcode 654. Maximum Binary Tree(python)

根据给定整数数组,使用深度优先搜索(DFS)递归构建最大二叉树。最大二叉树的构建过程是找到数组中的最大值作为根节点,然后分别对左右子数组进行相同操作。此算法在LeetCode上的运行时间为180ms,内存使用14.4MB。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:

  • Create a root node whose value is the maximum value in nums.
  • Recursively build the left subtree on the subarray prefix to the left of the maximum value.
  • Recursively build the right subtree on the subarray suffix to the right of the maximum value.

Return the maximum binary tree built from nums.

Example 1:
avater

Input: nums = [3,2,1,6,0,5]
Output: [6,3,5,null,2,0,null,null,1]
Explanation: The recursive calls are as follow:
- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].
    - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].
        - Empty array, so no child.
        - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].
            - Empty array, so no child.
            - Only one element, so child is a node with value 1.
    - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].
        - Only one element, so child is a node with value 0.
        - Empty array, so no child.

Example 2:

avater

Input: nums = [3,2,1]
Output: [3,null,2,null,1]

Note:

1 <= nums.length <= 1000
0 <= nums[i] <= 1000
All integers in nums are unique.

解析

根据题意,将 nums 变化为一个最大二叉树,其实看例子一就可以总结出规律使用 DFS 方式来进行解体,DFS 函数的基本逻辑就是将 nums 的最大值作为根 root ,其左边的数组不为空则为左子树,右边的数组不为空则为右子树,然后分别对左子树当前的列表和右子树当前列表执行相同的操作,最后返回 root 即可。

解答

# 方便理解版本
class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        def dfs(root, left, right):
            # if not root:
            #     return
            if left:
                mx_left = max(left)
                idx = left.index(mx_left)
                root.left = TreeNode(mx_left)
                dfs(root.left, left[:idx], left[idx+1:])
            if right:
                mx_right = max(right)
                idx = right.index(mx_right)
                root.right = TreeNode(mx_right)
                dfs(root.right, right[:idx], right[idx + 1:])
        mx = max(nums)
        idx = nums.index(mx)
        root = TreeNode(mx)
        dfs(root, nums[:idx], nums[idx+1:])
        return root
        
# 简洁版本
class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        def dfs(nums):
            if not nums:
                return
            mx = max(nums)
            idx = nums.index(mx)
            root = TreeNode(mx)
            root.left = dfs(nums[:idx])
            root.right = dfs(nums[idx+1:])
            return root
        return dfs(nums)   

运行结果

Runtime: 180 ms, faster than 88.01% of Python online submissions for Maximum Binary Tree.
Memory Usage: 14.4 MB, less than 6.51% of Python online submissions for Maximum Binary Tree.

原题链接:https://leetcode.com/problems/maximum-binary-tree/

您的支持是我最大的动力

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大丫丫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值