Skip to content

Commit d0e4aba

Browse files
committed
Added solution to create minimal bst with sorted array input
1 parent a45e80a commit d0e4aba

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.eprogrammerz.examples.algorithm.trees;
2+
3+
import org.junit.Test;
4+
5+
import java.util.Arrays;
6+
import java.util.List;
7+
8+
import static org.junit.Assert.assertEquals;
9+
10+
public class MinimalBST {
11+
public Node constructMinBST(List<Integer> vals) {
12+
if (vals == null || vals.isEmpty()) return null;
13+
14+
return constructMinBST(vals, 0, vals.size() - 1);
15+
}
16+
17+
public Node constructMinBST(List<Integer> vals, int start, int end) {
18+
if (start > end) return null;
19+
20+
int mid = (end - start) / 2 + start;
21+
22+
Node node = new Node(vals.get(mid));
23+
24+
node.left = constructMinBST(vals, start, mid - 1);
25+
node.right = constructMinBST(vals, mid + 1, end);
26+
27+
return node;
28+
}
29+
30+
@Test
31+
public void testConstructMinimalTree() {
32+
List<Integer> vals = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
33+
34+
/**
35+
* 4
36+
* / \
37+
* 2 6
38+
* / \ / \
39+
* 1 3 5 7
40+
*/
41+
Node tree = constructMinBST(vals);
42+
assertEquals(3, maxDepth(tree));
43+
}
44+
45+
public int maxDepth(Node tree) {
46+
if (tree == null) return 0;
47+
return Math.max(maxDepth(tree.left), maxDepth(tree.right)) + 1;
48+
}
49+
}

0 commit comments

Comments
 (0)