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
Binary Tree Longest Consecutive Sequence INPUT Binary Tree Structure: 1 3 2 4 5 Green = Consecutive Path root = [1,null,3,2,4,null, null,null,5] ALGORITHM STEPS 1 Start DFS Traverse tree from root 2 Check Consecutive If child = parent + 1 3 Track Length Increment or reset to 1 4 Update Maximum Keep track of max length DFS Trace: Node 1: len=1, max=1 Node 3: 3!=2, len=1 Node 2: 2!=4, len=1 Node 4: 4=3+1, len=2 Node 5: 5=4+1, len=3 max = 3 (3-->4-->5) FINAL RESULT Longest Consecutive Path: 3 4 5 Output: 3 OK - Path Found! 3 --> 4 --> 5 Time: O(n) | Space: O(h) n=nodes, h=height Key Insight: Optimized DFS passes the current consecutive length to children. If child value equals parent+1, increment the length; otherwise reset to 1. This avoids redundant traversals and achieves O(n) time. Each node is visited exactly once, making it optimal for finding the longest increasing path. TutorialsPoint - Binary Tree Longest Consecutive Sequence | Optimized DFS Approach
Asked in
Google 45 Facebook 32 Microsoft 28 Amazon 25
89.0K Views
Medium Frequency
~15 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