Binary Tree Longest Consecutive Sequence

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree, return the number of nodes on the longest **consecutive sequence path**. A consecutive sequence path is a downward path (from a parent to one of its children, repeatedly) where each node's value is exactly one greater than its parent's value on the path. The path may start at any node, not only the root, and it never moves back up the tree. A single node counts as a path of length 1. An empty tree has answer 0.

Examples

Input: root = [5,6,2,7,null,3,null,null,8]
Output: 4
The path 5 -> 6 -> 7 -> 8 increases by one at every step.
Input: root = [4,3,5,null,null,null,5]
Output: 2
4 -> 5 is consecutive; the next 5 does not continue it, and 4 -> 3 decreases.

Constraints

  • 0 <= number of nodes <= 3 * 10^4
  • -3 * 10^4 <= Node.val <= 3 * 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems