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

Commitc3fc701

Browse files
add a solution for 298
1 parent8b8019c commitc3fc701

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

‎src/main/java/com/fishercoder/solutions/_298.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,27 @@ private void dfs(TreeNode root, int curr, int target) {
2929
dfs(root.right,curr,root.val +1);
3030
}
3131
}
32+
33+
publicstaticclassSolution2 {
34+
/**
35+
* This is a better solution since it doesn't involve a global variable.
36+
*/
37+
publicintlongestConsecutive(TreeNoderoot) {
38+
returndfs(root,0,root.val);
39+
}
40+
41+
privateintdfs(TreeNoderoot,intcurr,inttarget) {
42+
if (root ==null) {
43+
return0;
44+
}
45+
if (root.val ==target) {
46+
curr++;
47+
}else {
48+
curr =1;
49+
}
50+
intleft =dfs(root.left,curr,root.val +1);
51+
intright =dfs(root.right,curr,root.val +1);
52+
returnMath.max(curr,Math.max(left,right));
53+
}
54+
}
3255
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
packagecom.fishercoder;
2+
3+
importcom.fishercoder.common.classes.TreeNode;
4+
importcom.fishercoder.common.utils.TreeUtils;
5+
importcom.fishercoder.solutions._298;
6+
importorg.junit.BeforeClass;
7+
importorg.junit.Test;
8+
9+
importjava.util.Arrays;
10+
11+
importstaticorg.junit.Assert.assertEquals;
12+
13+
publicclass_298Test {
14+
privatestatic_298.Solution1solution1;
15+
privatestatic_298.Solution2solution2;
16+
17+
@BeforeClass
18+
publicstaticvoidsetup() {
19+
solution1 =new_298.Solution1();
20+
solution2 =new_298.Solution2();
21+
}
22+
23+
@Test
24+
publicvoidtest1() {
25+
TreeNoderoot =TreeUtils.constructBinaryTree(Arrays.asList(1,null,3,2,4,null,null,null,5));
26+
assertEquals(3,solution1.longestConsecutive(root));
27+
assertEquals(3,solution2.longestConsecutive(root));
28+
}
29+
30+
@Test
31+
publicvoidtest2() {
32+
TreeNoderoot =TreeUtils.constructBinaryTree(Arrays.asList(2,null,3,2,null,1));
33+
assertEquals(2,solution1.longestConsecutive(root));
34+
assertEquals(2,solution2.longestConsecutive(root));
35+
}
36+
37+
@Test
38+
publicvoidtest3() {
39+
TreeNoderoot =TreeUtils.constructBinaryTree(Arrays.asList(1,2,3,null,null,4,4,null,5,null,null,6));
40+
TreeUtils.printBinaryTree(root);
41+
assertEquals(4,solution1.longestConsecutive(root));
42+
assertEquals(4,solution2.longestConsecutive(root));
43+
}
44+
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp