forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_298.java
55 lines (48 loc) · 1.45 KB
/
_298.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _298 {
public static class Solution1 {
private int max = 1;
public int longestConsecutive(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root, 0, root.val);
return max;
}
private void dfs(TreeNode root, int curr, int target) {
if (root == null) {
return;
}
if (root.val == target) {
curr++;
} else {
curr = 1;
}
max = Math.max(max, curr);
dfs(root.left, curr, root.val + 1);
dfs(root.right, curr, root.val + 1);
}
}
public static class Solution2 {
/**
* This is a better solution since it doesn't involve a global variable.
*/
public int longestConsecutive(TreeNode root) {
return dfs(root, 0, root.val);
}
private int dfs(TreeNode root, int curr, int target) {
if (root == null) {
return 0;
}
if (root.val == target) {
curr++;
} else {
curr = 1;
}
int left = dfs(root.left, curr, root.val + 1);
int right = dfs(root.right, curr, root.val + 1);
return Math.max(curr, Math.max(left, right));
}
}
}