Skip to content

Commit c3fc701

Browse files
add a solution for 298
1 parent 8b8019c commit c3fc701

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

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

+23
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+
public static class Solution2 {
34+
/**
35+
* This is a better solution since it doesn't involve a global variable.
36+
*/
37+
public int longestConsecutive(TreeNode root) {
38+
return dfs(root, 0, root.val);
39+
}
40+
41+
private int dfs(TreeNode root, int curr, int target) {
42+
if (root == null) {
43+
return 0;
44+
}
45+
if (root.val == target) {
46+
curr++;
47+
} else {
48+
curr = 1;
49+
}
50+
int left = dfs(root.left, curr, root.val + 1);
51+
int right = dfs(root.right, curr, root.val + 1);
52+
return Math.max(curr, Math.max(left, right));
53+
}
54+
}
3255
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.classes.TreeNode;
4+
import com.fishercoder.common.utils.TreeUtils;
5+
import com.fishercoder.solutions._298;
6+
import org.junit.BeforeClass;
7+
import org.junit.Test;
8+
9+
import java.util.Arrays;
10+
11+
import static org.junit.Assert.assertEquals;
12+
13+
public class _298Test {
14+
private static _298.Solution1 solution1;
15+
private static _298.Solution2 solution2;
16+
17+
@BeforeClass
18+
public static void setup() {
19+
solution1 = new _298.Solution1();
20+
solution2 = new _298.Solution2();
21+
}
22+
23+
@Test
24+
public void test1() {
25+
TreeNode root = 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+
public void test2() {
32+
TreeNode root = 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+
public void test3() {
39+
TreeNode root = 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)