Magicsheet logo

Binary Tree Longest Consecutive Sequence II

Medium
25%
Updated 8/1/2025

Binary Tree Longest Consecutive Sequence II

What is this problem about?

Building on its predecessor, the Binary Tree Longest Consecutive Sequence II interview question takes the challenge to the next level. In this version, the consecutive sequence can be either increasing or decreasing, and more importantly, the path does not have to be strictly top-down (parent to child). It can pass through a node from its left child to its right child (through the parent). This makes it a significantly more complex tree-traversal problem that requires tracking multiple states simultaneously at each node.

Why is this asked in interviews?

Companies like Google and Uber ask this to test your ability to handle complex recursive returns. In most tree problems, you return a single value (like height or sum). Here, you need to return both the longest increasing and longest decreasing sequence lengths ending at the current node. It evaluates your capacity for "bottom-up" thinking and your ability to combine results from subproblems to solve a larger one.

Algorithmic pattern used

The Depth-First Search (DFS) or Post-order Traversal pattern is essential here. Since a path can go through a parent from one child to another, you must first gather information from both the left and right subtrees (bottom-up). Each node returns two values to its parent: the length of the longest increasing path and the longest decreasing path that ends at that node.

Example explanation

Consider a small subtree: 5 / 4 6

  1. From the left child (4): It returns that it has an increasing path of length 1 (itself) and a decreasing path of length 1.
  2. At the current node (5):
    • 5 is 4 + 1, so the increasing path from the left is 1 + 1 = 2.
    • From the right child (6): 6 is 5 + 1. So if we look from 6 to 5, it's a decreasing path. 5 can extend 6's decreasing path.
  3. The total path through 5 is (increasing path from left) + (decreasing path from right) - 1. In this case: 2 + 2 - 1 = 3 (Path: 4-5-6).

Common mistakes candidates make

The most common mistake is failing to realize that you need to return two separate values from each recursive call. Some try to use global variables, but that becomes messy when paths can branch. Another error is forgetting to reset the path length to 1 if a child is not consecutive with its parent. Finally, many candidates struggle with the math of combining paths that go "through" the parent.

Interview preparation tip

Practice returning arrays or custom objects from recursive functions. This is a common pattern in "Hard" tree problems. When a path can span across a root, always think about what information the parent needs from its children to make that connection.

Similar Questions