Appearance
654. 最大二叉树
js
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var constructMaximumBinaryTree = function(nums) {
if (!nums.length) return null
if (nums.length === 1) return new TreeNode(nums[0])
let max = -Number.MAX_VALUE
let maxIndex
// 找出最大值和最大值的索引
for (let i = 0;i < nums.length;i++) {
if (nums[i] > max) {
max = nums[i]
maxIndex = i
}
}
// 从最大值 切分为左右两块递归
const node = new TreeNode(max)
node.left = constructMaximumBinaryTree(nums.slice(0, maxIndex))
node.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1))
return node
};
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var constructMaximumBinaryTree = function(nums) {
if (!nums.length) return null
if (nums.length === 1) return new TreeNode(nums[0])
let max = -Number.MAX_VALUE
let maxIndex
// 找出最大值和最大值的索引
for (let i = 0;i < nums.length;i++) {
if (nums[i] > max) {
max = nums[i]
maxIndex = i
}
}
// 从最大值 切分为左右两块递归
const node = new TreeNode(max)
node.left = constructMaximumBinaryTree(nums.slice(0, maxIndex))
node.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1))
return node
};