给定一个不含重复元素的整数数组 nums 。一个以此数组直接递归构建的最大二叉树定义如下:
二叉树的根是数组 nums 中的最大元素。
左子树是通过数组中最大值左边部分递归构造出的最大二叉树。
右子树是通过数组中最大值右边部分递归构造出的最大二叉树。
返回有给定数组 nums 构建的最大二叉树 。
示例 1:
6
/ \
3 5
\ /
2 0
\
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:
3
\
2
\
1
输入:nums = [3,2,1]
输出:[3,null,2,null,1]
链接:https://leetcode-cn.com/problems/maximum-binary-tree
老递归算法了!
Python3
# 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]) -> TreeNode:
if len(nums) == 0:
return None
elif len(nums) == 1:
return TreeNode(nums[0])
else:
index = nums.index(max(nums))
res = TreeNode(nums[index])
left = nums[0:index]
right = nums[index+1:]
res.left = self.constructMaximumBinaryTree(left)
res.right = self.constructMaximumBinaryTree(right)
return res
该博客讨论了如何使用递归算法从给定的无重复整数数组构建最大二叉树。示例展示了如何根据数组的最大值及其左右子数组递归地创建树节点,并给出了具体的Python实现。
95

被折叠的 条评论
为什么被折叠?



