LeetCode 题解工作台
最大二叉树
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建: 创建一个根节点,其值为 nums 中的最大值。 递归地在最大值 左边 的 子数组前缀上 构建左子树。 递归地在最大值 右边 的 子数组后缀上 构建右子树。 返回 nums 构建的 最大二叉树 。 示例 1…
6
题型
7
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
先找到数组 的最大元素所在的位置 ,将 作为根节点,然后递归左右两侧的子数组,构建左右子树。 时间复杂度 ,空间复杂度 ,其中 是数组的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建:
- 创建一个根节点,其值为
nums中的最大值。 - 递归地在最大值 左边 的 子数组前缀上 构建左子树。
- 递归地在最大值 右边 的 子数组后缀上 构建右子树。
返回 nums 构建的 最大二叉树 。
示例 1:
输入:nums = [3,2,1,6,0,5]
输出:[6,3,5,null,2,0,null,null,1]
解释:递归调用如下所示:
- [3,2,1,6,0,5] 中的最大值是 6 ,左边部分是 [3,2,1] ,右边部分是 [0,5] 。
- [3,2,1] 中的最大值是 3 ,左边部分是 [] ,右边部分是 [2,1] 。
- 空数组,无子节点。
- [2,1] 中的最大值是 2 ,左边部分是 [] ,右边部分是 [1] 。
- 空数组,无子节点。
- 只有一个元素,所以子节点是一个值为 1 的节点。
- [0,5] 中的最大值是 5 ,左边部分是 [0] ,右边部分是 [] 。
- 只有一个元素,所以子节点是一个值为 0 的节点。
- 空数组,无子节点。
示例 2:
输入:nums = [3,2,1] 输出:[3,null,2,null,1]
提示:
1 <= nums.length <= 10000 <= nums[i] <= 1000nums中的所有整数 互不相同
解题思路
方法一:递归
先找到数组 的最大元素所在的位置 ,将 作为根节点,然后递归左右两侧的子数组,构建左右子树。
时间复杂度 ,空间复杂度 ,其中 是数组的长度。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:
def dfs(nums):
if not nums:
return None
val = max(nums)
i = nums.index(val)
root = TreeNode(val)
root.left = dfs(nums[:i])
root.right = dfs(nums[i + 1 :])
return root
return dfs(nums)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^2) for simple recursion due to repeated max searches, but O(n) with a monotonic stack. Space complexity is O(n) for recursion stack or explicit data structures. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect you to explain recursive subtree construction and element selection.
- question_mark
They may probe for iterative alternatives using a stack to reduce repeated max searches.
- question_mark
Clarification questions often focus on handling empty arrays or single-element subarrays.
常见陷阱
外企场景- error
Not correctly partitioning the array, leading to misplaced children.
- error
Repeatedly scanning for the maximum without optimization, causing O(n^2) time.
- error
Ignoring edge cases like empty subarrays or single-element segments.
进阶变体
外企场景- arrow_right_alt
Construct a maximum binary tree from a linked list instead of an array.
- arrow_right_alt
Build a minimum binary tree by selecting the smallest element as root at each step.
- arrow_right_alt
Return the preorder or inorder traversal of the maximum binary tree without building it explicitly.