1. 程式人生 > >JavaScript刷LeetCode -- 654. Maximum Binary Tree【Medium】

JavaScript刷LeetCode -- 654. Maximum Binary Tree【Medium】

一、題目

  Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  • The root is the maximum number in the array.
  • The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  • The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

  Construct the maximum tree by the given array and output the root node of this tree.

二、題目大意

通過給定的陣列構建一個最大的二叉樹,這個最大的二叉樹必須滿足根節點的值大於左右子節點的值。

三、解題思路

遞迴求解

四、程式碼實現

const constructMaximumBinaryTree = nums => {
  let max = nums.length
  if (max === 0) {
    return null
  }
  const root = new TreeNode()
  let maxValue = nums[0]
  let index = 0
  for (let i = 0; i < max; i++) {
    const item = nums[i]
    if (item > maxValue) {
      index = i
      maxValue = item
    }
  }
  root.val = maxValue
  root.left = constructMaximumBinaryTree(nums.slice(0, index))
  root.right = constructMaximumBinaryTree(nums.slice(index + 1, max))
  return root
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。