Skip to content

Commit 557ad83

Browse files
committed
Added convert sorted array to bst - easy
1 parent 499d704 commit 557ad83

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Time: O(log (n))
3+
* Space: O(n)
4+
*/
5+
class Solution {
6+
public TreeNode sortedArrayToBST(int[] nums) {
7+
if (nums.length == 0 || nums == null) return null;
8+
return convert(nums, 0, nums.length - 1);
9+
}
10+
public TreeNode convert(int[] array, int start, int end) {
11+
if (start > end) return null;
12+
// Calculate median index
13+
int mid = start + (end - start) / 2;
14+
// Set median val to root
15+
TreeNode root = new TreeNode(array[mid]);
16+
// Determine left and right children
17+
// S for 'start', m for 'mid' and e for 'end'
18+
// s m e
19+
// x - x - x - x - x - x - x
20+
// You can see that the left side ranges from start to mid
21+
// And right side ranges from mid to end
22+
root.left = convert(array, start, mid - 1);
23+
root.right = convert(array, mid + 1, end);
24+
return root;
25+
}
26+
27+
28+
}

0 commit comments

Comments
 (0)