-
Notifications
You must be signed in to change notification settings - Fork 0
/
MinHeightBST.java
52 lines (47 loc) · 1.26 KB
/
MinHeightBST.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
class Program {
// O(nlog(n)) time | O(n) space - where n is the length of the array
public static BST minHeightBst(List<Integer> array) {
// Write your code here.
return constructMinHeightBst(array, null, 0, array.size() - 1);
}
private static BST constructMinHeightBst(List<Integer> array, BST root, int startIdx, int endIdx) {
if (startIdx > endIdx) {
return null;
}
int midIdx = startIdx + (endIdx - startIdx) / 2;
if (root == null) {
root = new BST(array.get(midIdx));
} else {
root.insert(array.get(midIdx)); // takes O(log(n)) time
}
constructMinHeightBst(array, root, startIdx, midIdx - 1);
constructMinHeightBst(array, root, midIdx + 1, endIdx);
return root;
}
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
left = null;
right = null;
}
public void insert(int value) {
if (value < this.value) {
if (left == null) {
left = new BST(value);
} else {
left.insert(value);
}
} else {
if (right == null) {
right = new BST(value);
} else {
right.insert(value);
}
}
}
}
}