From 50ed227f5500d627d40c5dfcd96a0fe584ee0000 Mon Sep 17 00:00:00 2001 From: kok-s0s <2694308562@qq.com> Date: Sun, 4 Jul 2021 18:19:20 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BE=9BJavaScript=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E7=9A=84=E3=80=8A=E5=B0=86=E6=9C=89=E5=BA=8F=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E8=BD=AC=E6=8D=A2=E4=B8=BA=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2?= =?UTF-8?q?=E6=A0=91=E3=80=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...将有序数组转换为二叉搜索树.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0108.将有序数组转换为二叉搜索树.md b/problems/0108.将有序数组转换为二叉搜索树.md index b8861b24..b38330b9 100644 --- a/problems/0108.将有序数组转换为二叉搜索树.md +++ b/problems/0108.将有序数组转换为二叉搜索树.md @@ -279,6 +279,36 @@ func sortedArrayToBST(nums []int) *TreeNode { } ``` +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 sortedArrayToBST = function (nums) { + const buildTree = (Arr, left, right) => { + if (left > right) + return null; + + let mid = Math.floor(left + (right - left) / 2); + + let root = new TreeNode(Arr[mid]); + root.left = buildTree(Arr, left, mid - 1); + root.right = buildTree(Arr, mid + 1, right); + return root; + } + return buildTree(nums, 0, nums.length - 1); +}; +```