Binary Tree Longest Consecutive Sequence
Example
Input:
1
\
3
/ \
2 4
\
5
Output: 3
Explanation:
Longest consecutive sequence path is
3-4-5, so return 3.Note
Code
Last updated
Input:
1
\
3
/ \
2 4
\
5
Output: 3
Explanation:
Longest consecutive sequence path is
3-4-5, so return 3.Last updated
Input:
2
\
3
/
2
/
1
Output: 2
Explanation:
Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.class Solution {
private int res;
public int longestConsecutive(TreeNode root) {
res = 0;
dfs(root, null, 0);
return res;
}
private void dfs(TreeNode root, TreeNode parent, int len) {
if (root == null) {
return;
}
if (parent == null || parent.val + 1 == root.val) {
len++;
} else {
len = 1;
}
res = Math.max(res, len);
dfs(root.left, root, len);
dfs(root.right, root, len);
}
}class Solution {
private int res;
public int longestConsecutive(TreeNode root) {
res = 0;
dfs(root);
return res;
}
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int left = dfs(root.left);
int right = dfs(root.right);
int curr = 1;
if (root.left != null && root.val + 1 == root.left.val) {
curr = Math.max(curr, left + 1);
}
if (root.right != null && root.val + 1 == root.right.val) {
curr = Math.max(curr, right + 1);
}
res = Math.max(res, curr);
return curr;
}
}