Skip to content

Commit 73e94a0

Browse files
committed
add convert-sorted-array-to-binary-search-tree script.
1 parent d8a6a18 commit 73e94a0

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {number[]} nums
10+
* @return {TreeNode}
11+
*/
12+
const sortedArrayToBST = function(nums) {
13+
if (nums.length == 0) {
14+
return null;
15+
}
16+
const head = helper(nums, 0, nums.length - 1);
17+
return head;
18+
};
19+
20+
function helper(num, low, high) {
21+
if (low > high) {
22+
// Done
23+
return null;
24+
}
25+
let mid = Math.floor((low + high) / 2);
26+
let node = new TreeNode(num[mid]);
27+
node.left = helper(num, low, mid - 1);
28+
node.right = helper(num, mid + 1, high);
29+
return node;
30+
}

0 commit comments

Comments
 (0)