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

Longest Consecutive Downward Run

binary trees · depth-first search · path tracking

A downward run is a path that starts at some node and keeps moving to a child, where every child's value is exactly one more than its parent's value. Given the root of a binary tree, return the number of nodes on the longest downward run. A single node is a run of length 1; the 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. The step 1 -> 3 breaks the run.
    2
     \
      3
     /
    2
   /
  1

Input:  root = build_tree([2, None, 3, 2, None, 1])
Output: 2
Explanation: 2 -> 3 is the longest run; runs only go downward, and only by +1.

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Extend or restart a running length at each child
  • Track the best length across all branches
  • Handle the empty tree and a single node
Starting Python…