Binary Tree Longest Consecutive Sequence II - Problem
Binary Tree Longest Consecutive Sequence II

You are given the root of a binary tree. Your task is to find the length of the longest consecutive path in the tree.

A consecutive path is defined as a path where the values of consecutive nodes differ by exactly 1. This path can be either:
Increasing: [1,2,3,4]
Decreasing: [4,3,2,1]

The key twist is that the path can follow a child-Parent-child pattern, not just parent-child. This means the longest path might go up from a leaf, through ancestors, then down to another leaf.

Goal: Return the length of the longest consecutive sequence in the tree.

Example: In a tree with nodes [2,1,3], the consecutive paths are [1,2,3] (length 3) going from left child → parent → right child.

Input & Output

example_1.py — Python
$ Input: [1,2,3]
Output: 2
💡 Note: The longest consecutive path is [1,2] or [2,3], both have length 2. The tree structure is: 1 as root, 2 as left child, 3 as right child.
example_2.py — Python
$ Input: [2,1,3]
Output: 3
💡 Note: The longest consecutive path is [1,2,3] with length 3. This path goes: left child (1) → parent (2) → right child (3), demonstrating the child-parent-child pattern.
example_3.py — Python
$ Input: [1]
Output: 1
💡 Note: Single node tree has only one possible path of length 1, which is the node itself.

Constraints

  • The number of nodes in the tree is in the range [0, 3 * 104]
  • -3 * 104 <= Node.val <= 3 * 104
  • The tree can have negative values
  • A single node has a consecutive sequence length of 1

Visualization

Tap to expand
Checkpoint 11Checkpoint 22Checkpoint 33Longest Trail: 1 → 2 → 3 (Length: 3)Trail Finding Strategy1. Visit each checkpoint once, tracking ascending/descending paths2. At junction points, combine paths from different directions for longer routes
Understanding the Visualization
1
Start at Leaf Checkpoints
Begin at leaf nodes (endpoints of trails) - each starts with path length 1
2
Extend Paths Upward
As you move up to parent checkpoints, extend consecutive paths based on number differences
3
Combine at Junction Points
At internal nodes, combine ascending and descending paths to create longer cross-mountain routes
4
Track Maximum Trail
Keep track of the longest consecutive trail found during the entire exploration
Key Takeaway
🎯 Key Insight: By tracking both increasing and decreasing consecutive paths at each node during a single DFS traversal, we can efficiently find the longest consecutive sequence that may span across different subtrees through parent nodes.
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 21
34.2K Views
Medium-High Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen