https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {number[]} nums
* @return {TreeNode}
*/
var sortedArrayToBST = function(nums) {
const helper = (nums, low, high) => {
if (low > high) {
return null
}
let mid = Math.ceil(low + (high - low) / 2) // use Math.ceil() not Math.floor()!!
let node = new TreeNode(nums[mid])
node.left = helper(nums, low, mid - 1)
node.right = helper(nums, mid + 1, high)
return node
}
return helper(nums, 0, nums.length - 1)
};