首发于 语雀文档@blueju

    代码:

    1. /**
    2. * Definition for a binary tree node.
    3. * class TreeNode {
    4. * val: number
    5. * left: TreeNode | null
    6. * right: TreeNode | null
    7. * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
    8. * this.val = (val===undefined ? 0 : val)
    9. * this.left = (left===undefined ? null : left)
    10. * this.right = (right===undefined ? null : right)
    11. * }
    12. * }
    13. */
    14. function constructMaximumBinaryTree(nums: number[]): TreeNode | null {
    15. const [maxValue, maxValueIndex] = useMax(nums)
    16. const tree = new TreeNode()
    17. tree.val = maxValue
    18. tree.left = constructMaximumBinaryTree(nums.slice(0, maxValueIndex))
    19. tree.right = constructMaximumBinaryTree(nums.slice(maxValueIndex + 1))
    20. return tree
    21. };
    22. function useMax(nums) {
    23. const maxValue = Math.max(...nums)
    24. const maxValueIndex = nums.findIndex(item => item === maxValue)
    25. return [maxValue, maxValueIndex]
    26. }