首发于 语雀文档@blueju
代码:
/*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*/function constructMaximumBinaryTree(nums: number[]): TreeNode | null {const [maxValue, maxValueIndex] = useMax(nums)const tree = new TreeNode()tree.val = maxValuetree.left = constructMaximumBinaryTree(nums.slice(0, maxValueIndex))tree.right = constructMaximumBinaryTree(nums.slice(maxValueIndex + 1))return tree};function useMax(nums) {const maxValue = Math.max(...nums)const maxValueIndex = nums.findIndex(item => item === maxValue)return [maxValue, maxValueIndex]}
