Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 601
Expand file tree
/
Copy pathConvertSortedArraytoBinarySearchTree.java
More file actions
Latest commit
26 lines (23 loc) · 803 Bytes
/
Copy pathConvertSortedArraytoBinarySearchTree.java
File metadata and controls
26 lines (23 loc) · 803 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
packageproblems.medium;
importproblems.utils.TreeNode;
/**
* Created by sherxon on 1/5/17.
*/
publicclassConvertSortedArraytoBinarySearchTree {
/**
* As an array is sorted, we can find root of array by finding middle element in constant time.
* then divide both left and right parts of array and apply the method again to find root of subtrees
*/
publicTreeNodesortedArrayToBST(int[] a) {
if (a.length == 0) returnnull;
returnhelper(a, 0, a.length - 1);
}
privateTreeNodehelper(int[] a, intlo, inthi) {
if (lo > hi) returnnull;
intmid = lo + (hi - lo) / 2;
TreeNodehead = newTreeNode(a[mid]);
head.left = helper(a, lo, mid - 1);
head.right = helper(a, mid + 1, hi);
returnhead;
}
}