Skip to content

Commit 40ae952

Browse files
committed
Convert Sorted Array to Binary Search Tree
1 parent 1d448aa commit 40ae952

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Diff for: Convert Sorted Array to Binary Search Tree.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
2+
3+
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
4+
5+
6+
Example:
7+
8+
Given the sorted array: [-10,-3,0,5,9],
9+
10+
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
11+
12+
0
13+
/ \
14+
-3 9
15+
/ /
16+
-10 5*/
17+
18+
/**
19+
* Definition for a binary tree node.
20+
* function TreeNode(val) {
21+
* this.val = val;
22+
* this.left = this.right = null;
23+
* }
24+
*/
25+
/**
26+
* @param {number[]} nums
27+
* @return {TreeNode}
28+
*/
29+
var sortedArrayToBST = function(nums) {
30+
if(nums[0] != null){
31+
var mid = Math.floor(nums.length/2)
32+
var tree = new TreeNode(nums[mid])
33+
tree.left = sortedArrayToBST(nums.slice(0,mid))
34+
tree.right = sortedArrayToBST(nums.slice(mid+1))
35+
return tree
36+
}
37+
else return null
38+
};

0 commit comments

Comments
 (0)