Skip to content

Commit 38589ac

Browse files
add a solution for 1008
1 parent b315c79 commit 38589ac

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/main/java/com/fishercoder/solutions/_1008.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,30 @@ private TreeNode bstFromPreorder(int[] preorder, int bound) {
2323
return root;
2424
}
2525
}
26+
27+
public static class Solution2 {
28+
/**
29+
* I'm happy to have come up with this solution completely on my own on 10/13/2021.Enjoy the beauty of recursion!
30+
*/
31+
public TreeNode bstFromPreorder(int[] preorder) {
32+
return bstFromPreorder(preorder, 0, preorder.length);
33+
}
34+
35+
private TreeNode bstFromPreorder(int[] preorder, int start, int end) {
36+
if (start >= end) {
37+
return null;
38+
}
39+
TreeNode root = new TreeNode(preorder[start]);
40+
int i = start + 1;
41+
for (; i < end; i++) {
42+
if (preorder[i] > preorder[start]) {
43+
break;
44+
}
45+
}
46+
root.left = bstFromPreorder(preorder, start + 1, i);
47+
root.right = bstFromPreorder(preorder, i, end);
48+
return root;
49+
}
50+
51+
}
2652
}

src/test/java/com/fishercoder/_1008Test.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,24 @@
1111

1212
public class _1008Test {
1313
private static _1008.Solution1 solution1;
14+
private static _1008.Solution2 solution2;
1415
private static int[] preorder;
1516
private static TreeNode expected;
1617
private static TreeNode actual;
1718

1819
@Test
1920
public void test1() {
2021
solution1 = new _1008.Solution1();
22+
solution2 = new _1008.Solution2();
2123
preorder = new int[]{8, 5, 1, 7, 10, 12};
2224
expected = TreeUtils.constructBinaryTree(Arrays.asList(8, 5, 10, 1, 7, null, 12));
2325
TreeUtils.printBinaryTree(expected);
2426
actual = solution1.bstFromPreorder(preorder);
2527
TreeUtils.printBinaryTree(actual);
2628
assertEquals(expected, actual);
29+
actual = solution2.bstFromPreorder(preorder);
30+
TreeUtils.printBinaryTree(actual);
31+
assertEquals(expected, actual);
2732
}
2833

2934
}

0 commit comments

Comments
 (0)