Skip to content
On this page

最大二叉树

Question

给定一个不重复的整数数组 nums最大二叉树 可以用下面的算法从 nums 递归地构建:

创建一个根节点,其值为 nums 中的最大值。 递归地在最大值 左边 的 子数组前缀上 构建左子树。 递归地在最大值 右边 的 子数组后缀上 构建右子树。 返回 nums 构建的 最大二叉树 。

js
var constructMaximumBinaryTree = function(nums) {
    if(nums.length===0) return null
    let index = nums.findIndex((element)=>     //找到最大值的索引下标
        element === Math.max(...nums)
    )
    const root = new TreeNode()
    root.val = nums[index]
    console.log(root)
    const leftnums = nums.slice(0,index)
    const rightnums = nums.slice(index+1,nums.length)
    root.left = constructMaximumBinaryTree(leftnums)
    root.right = constructMaximumBinaryTree(rightnums)
    return root
};