Binary Tree Longest Consecutive Sequence - Problem
You're given the root of a binary tree and need to find the longest consecutive sequence path within it. Think of it as finding the longest chain of numbers that increase by exactly 1 at each step!
A consecutive sequence path is a path where:
- Values increase by exactly 1 along the path (e.g., 1→2→3→4)
- The path follows parent-to-child direction only (no going back up)
- The path can start at any node in the tree
Goal: Return the length of the longest such consecutive sequence path.
For example, in a tree with nodes [1,null,3,2,4,null,null,null,5], the longest consecutive path is 3→4→5 with length 3.
Input & Output
example_1.py — Basic Tree
$
Input:
[1,null,3,2,4,null,null,null,5]
›
Output:
3
💡 Note:
The longest consecutive sequence path is 3-4-5, so return 3. The tree structure shows 1 has right child 3, which has children 2 and 4, and 4 has right child 5.
example_2.py — Disconnected Sequences
$
Input:
[2,null,3,2,null,1]
›
Output:
2
💡 Note:
The longest consecutive sequence path is 2-3, so return 2. Note that there are two separate nodes with value 2, but we can only follow parent-to-child paths.
example_3.py — Single Node
$
Input:
[1]
›
Output:
1
💡 Note:
Single node tree has a consecutive sequence of length 1 (just the node itself).
Constraints
- The number of nodes in the tree is in the range [0, 3 × 104]
- -3 × 104 ≤ Node.val ≤ 3 × 104
- Path direction: Can only go from parent to child (no backtracking)
Visualization
Tap to expand
Understanding the Visualization
1
Start the Family Tree Exploration
Begin at the root of the family tree with initial consecutive count of 1
2
Check Each Parent-Child Relationship
For each parent-child pair, check if child's number = parent's number + 1
3
Maintain the Consecutive Chain
If consecutive, extend the chain length; otherwise, start a new chain from this person
4
Track the Longest Dynasty
Keep track of the longest consecutive chain found throughout the exploration
Key Takeaway
🎯 Key Insight: By tracking consecutive length during a single tree traversal, we avoid redundant work and achieve optimal O(n) time complexity while finding the longest consecutive sequence path.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code