-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbstProblem.js
More file actions
34 lines (30 loc) · 905 Bytes
/
Copy pathbstProblem.js
File metadata and controls
34 lines (30 loc) · 905 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 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}
*/
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
let sortedArrayToBST = function (nums) {
const fn = (nums, left, right) => {
if (left >= right) return null;
const mid = Math.floor((left + right) / 2);
return new TreeNode(
nums[mid],
fn(nums, left, mid),
fn(nums, mid + 1, right)
);
};
return fn(nums, 0, nums.length);
};
console.log("solution 1:", sortedArrayToBST([1, 4, 5, 6, 2, 5, 6, 6]));