← Questions
Longest consecutive sequence path in a binary tree
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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 haveval,leftandright. An empty tree returns0; a single node returns1.
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 + 1ifnode.val == parent.val + 1, else1; 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 -> 3as left child, root, right child gives3). Return for each node the longest increasing and decreasing runs going down, and combine them asinc + dec - 1. - Return the path itself.
- Allow steps of
+1or-1freely 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
