Longest Consecutive Sequence
Given a binary tree, find the length of the longest consecutive sequence path. The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections.
- Time: O(n)
- Space: O(1)
class LongestConsecutive {
int max = 0;
public int longestConsecutive(TreeNode root) {
dfs(root, root.val + 1, 1);
return max;
}
private void dfs(TreeNode root, int target, int count) {
if (root == null) {
return;
}
count = root.val == target ? count + 1 : 1;
max = Math.max(max, count);
dfs(root.left, target + 1, count);
dfs(root.right, target + 1, count);
}
}