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 II INPUT Binary Tree Structure 1 2 3 2 4 root = [1,2,3,null,null,2,4] null children Find longest consecutive path (increasing or decreasing) ALGORITHM STEPS 1 DFS Post-Order Process children first, then current node 2 Track Two Values inc: increasing seq length dec: decreasing seq length 3 Check Consecutiveness If child.val - node.val = 1 or node.val - child.val = 1 4 Combine at Node Child-Parent-Child path: left_inc + right_dec + 1 Return from each node: (inc, dec) values Node 2(left): (1,1) Node 2(sub): (1,1) Node 4: (1,1) Node 3: (2,2) FINAL RESULT Longest Path Found: 1 3 2 2 4 Path: 2 --> 3 --> 1 (or 1 --> 3 --> 2) Output 3 Key Insight: The trick is returning TWO values (inc, dec) from each DFS call. At each node, we can form a child-parent-child path by combining: left_inc + right_dec + 1 OR left_dec + right_inc + 1. This allows us to find paths going up through a node and down the other side in O(n) time. TutorialsPoint - Binary Tree Longest Consecutive Sequence II | Optimized Single Pass DFS
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