Binary Tree Longest Consecutive Sequence - Problem
Given the root of a binary tree, return the length of the longest consecutive sequence path.
A consecutive sequence path is a path where the values increase by one along the path. Note that the path can start at any node in the tree, and you cannot go from a node to its parent in the path.
The path must be from parent to child (cannot go upward in paths).
Input & Output
Example 1 — Basic Tree
$
Input:
root = [1,null,3,2,4,null,null,null,5]
›
Output:
3
💡 Note:
Longest consecutive sequence path is 3-4-5, so return 3. The path goes: 3→4→5.
Example 2 — No Long Sequence
$
Input:
root = [2,null,3,2,null,1]
›
Output:
2
💡 Note:
Longest consecutive sequence path is 2-3, so return 2. Note that 3-2-1 is not a valid path since we must go from parent to child.
Example 3 — Single Node
$
Input:
root = [1]
›
Output:
1
💡 Note:
Single node forms a sequence of length 1.
Constraints
- The number of nodes in the tree is in the range [1, 3 × 104]
- -3 × 104 ≤ Node.val ≤ 3 × 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with various integer values
2
Find Consecutive Paths
Look for paths where each child = parent + 1
3
Return Maximum Length
Length of longest consecutive sequence found
Key Takeaway
🎯 Key Insight: Use DFS to traverse the tree once, checking if each node continues the consecutive sequence from its parent (value = parent + 1)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code