Skip to content

最大二叉树

LeetCode-654

js
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
var constructMaximumBinaryTree = function(nums) {
  function rec(arr = []) {
    // 取出最大值
    const maxNum = Math.max.apply(null, nums)
    // 找到最大值index
    const index = nums.findIndex(item => item === maxNum)
    // 获取左边的数组
    const leftArr = nums.slice(0, index)
    // 获取右边的数组
    const rightArr = nums.slice(index+1)
    // 构建根节点
    let node = new TreeNode(maxNum)
    // 如果左边数组存在则构建左子树
    if(leftArr.length) node.left = constructMaximumBinaryTree(leftArr)
    // 如果右边数组存在则构建右子树
    if(rightArr.length) node.right = constructMaximumBinaryTree(rightArr)
    // 返回根节点
    return node
  }
  return rec(nums)
};