Binary Tree Longest Consecutive Sequence II - Problem

Given the root of a binary tree, return the length of the longest consecutive path in the tree.

A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] are both considered valid, but the path [1,2,4,3] is not valid.

The path can be in the child-Parent-child order, where not necessarily be parent-child order.

Input & Output

Example 1 — Path Through Root
$ Input: root = [1,2,3,null,null,2,4]
Output: 3
💡 Note: The longest consecutive path is 2→3→4 with length 3. This path goes through the right subtree.
Example 2 — Single Node
$ Input: root = [2]
Output: 1
💡 Note: Tree has only one node, so the longest consecutive path has length 1.
Example 3 — No Consecutive Path
$ Input: root = [1,3,5]
Output: 1
💡 Note: No consecutive path exists (values differ by more than 1), so return 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 IIInput Tree12324Consecutive Paths234Path: 2→3→4Output3Length = 3Find longest path where adjacent nodes differ by exactly 1🎯 Key Insight: Path can go through any node combining inc/dec sequences
Understanding the Visualization
1
Input Tree
Binary tree with node values
2
Find Paths
Identify all possible consecutive sequences
3
Return Length
Length of longest consecutive path
Key Takeaway
🎯 Key Insight: The longest consecutive path can pass through any node, combining increasing and decreasing sequences from its subtrees
Asked in
Google 25 Facebook 18 Amazon 15
32.0K Views
Medium Frequency
~25 min Avg. Time
845 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