654. 最大二叉树

给定一个不含重复元素的整数数组 nums 。一个以此数组直接递归构建的 最大二叉树 定义如下:

二叉树的根是数组 nums 中的最大元素。
左子树是通过数组中 最大值左边部分 递归构造出的最大二叉树。
右子树是通过数组中 最大值右边部分 递归构造出的最大二叉树。

链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
if (!nums || nums.length === 0) return null
let maxVal = 0
let maxIndex = 0
const len = nums.length
for(let i = 0; i < nums.length;i++) {
if (maxVal < nums[i]) {
maxVal = nums[i]
maxIndex = i
}
}
const root = new TreeNode(maxVal)
root.left = constructMaximumBinaryTree(nums.slice(0, maxIndex))
root.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1, len))
return root
}