← Questions

Longest consecutive sequence path in a binary tree

0
GoogleCodingLast asked Apr 2026

A coding interview question asked in Google's onsite coding round, last asked Apr 2026. It tests trees and dfs.

Given the root of a binary tree, return the length (in nodes) of the longest downward path, from a parent to a child and so on, in which each value is exactly one greater than the value before it.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • longest_consecutive(root: TreeNode | None) -> int — nodes have val, left and right. An empty tree returns 0; a single node returns 1.

Example

    1
     \
      3
     / \
    2   4
         \
          5
longest_consecutive(root)  ->  3      # 3 -> 4 -> 5

    1
   / \
  2   3
longest_consecutive(root)  ->  2      # 1 -> 2 (1 -> 3 skips a value)

longest_consecutive(None)  ->  0

Constraints

  • Up to 3 * 10^4 nodes; values fit in 32-bit integers.
  • The path must go downward and may start at any node.

Clarifying questions

  • Does the path have to start at the root?
  • Strictly +1 per step, or any increasing sequence?
  • Is length counted in nodes or edges?

What a strong answer covers

  • A DFS that passes down the current run length: run = parent_run + 1 if node.val == parent.val + 1, else 1; keep the maximum. O(n) time, O(h) space.
  • Or a post-order version that returns the run starting at each node.
  • Tests: empty tree, single node, decreasing values, a run that restarts in the middle.

Follow-ups

  • The path may go in any direction: up from one child through a node and down into the other, increasing or decreasing by one at each step (for example 1 -> 2 -> 3 as left child, root, right child gives 3). Return for each node the longest increasing and decreasing runs going down, and combine them as inc + dec - 1.
  • Return the path itself.
  • Allow steps of +1 or -1 freely along a downward path.

Where it's asked

  • Google · Onsite coding · Last asked Apr 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)

What it tests

trees · dfs

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding