Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit38589ac

Browse files
add a solution for 1008
1 parentb315c79 commit38589ac

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
returnroot;
2424
}
2525
}
26+
27+
publicstaticclassSolution2 {
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+
publicTreeNodebstFromPreorder(int[]preorder) {
32+
returnbstFromPreorder(preorder,0,preorder.length);
33+
}
34+
35+
privateTreeNodebstFromPreorder(int[]preorder,intstart,intend) {
36+
if (start >=end) {
37+
returnnull;
38+
}
39+
TreeNoderoot =newTreeNode(preorder[start]);
40+
inti =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+
returnroot;
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
publicclass_1008Test {
1313
privatestatic_1008.Solution1solution1;
14+
privatestatic_1008.Solution2solution2;
1415
privatestaticint[]preorder;
1516
privatestaticTreeNodeexpected;
1617
privatestaticTreeNodeactual;
1718

1819
@Test
1920
publicvoidtest1() {
2021
solution1 =new_1008.Solution1();
22+
solution2 =new_1008.Solution2();
2123
preorder =newint[]{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)

[8]ページ先頭

©2009-2025 Movatter.jp