Problem 402843 · medium · Phase 04 Non-Linear Data Structures

Longest Run of Consecutive Values

binary tree · recursion · depth-first search

A consecutive run is a downward path (parent to child at every step) in which each value is exactly one more than the previous one. Return the number of nodes in the longest consecutive run. A single node is a run of length 1; an empty tree gives 0.

Examples

  1
   \
    3
   / \
  2   4
       \
        5

Input:  root = build_tree([1, None, 3, 2, 4, None, None, None, 5])
Output: 3
Explanation: 3 -> 4 -> 5.

Input:  root = build_tree([2, None, 3, 2, None, 1])
Output: 2
Explanation: 2 -> 3; the run cannot continue to 2 or 1.

Constraints

  • 0 <= number of nodes <= 1000
  • -1000 <= node.val <= 1000

Goals

  • Extend a run only when the child's value is exactly one more than the parent's
  • Track the best run globally while passing the current run downward
Starting Python…