From d6ab48534d80a506b0e60df8196c9b5e2c802b10 Mon Sep 17 00:00:00 2001 From: kok-s0s <2694308562@qq.com> Date: Sat, 19 Jun 2021 22:16:42 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9C=80=E5=A4=A7=E4=BA=8C=E5=8F=89=E6=A0=91Ja?= =?UTF-8?q?vaScript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0654.最大二叉树.md | 36 ++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index f0d3e594..4e1e7a72 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -311,6 +311,42 @@ func findMax(nums []int) (index int){ } ``` +JavaScript版本 + +```javascript +/** + * 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) + * } + */ +/** + * @param {number[]} nums + * @return {TreeNode} + */ +var constructMaximumBinaryTree = function (nums) { + const BuildTree = (arr, left, right) => { + if (left > right) + return null; + let maxValue = -1; + let maxIndex = -1; + for (let i = left; i <= right; ++i) { + if (arr[i] > maxValue) { + maxValue = arr[i]; + maxIndex = i; + } + } + let root = new TreeNode(maxValue); + root.left = BuildTree(arr, left, maxIndex - 1); + root.right = BuildTree(arr, maxIndex + 1, right); + return root; + } + let root = BuildTree(nums, 0, nums.length - 1); + return root; +}; +```