Problem 410859 · medium · Level 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

        4
       / \
      6   9
     / \   \
    2   7   10
       /
      8

Input:  root = build_tree([4, 6, 9, 2, 7, None, 10, None, None, 8])
Output: 3
Explanation: 6 -> 7 -> 8. The step 4 -> 6 breaks the run, and 9 -> 10 stops at 2.
      7
     /
    8
     \
      7
     /
    6

Input:  root = build_tree([7, 8, None, None, 7, 6])
Output: 2
Explanation: 7 -> 8 is the longest run. 8 -> 7 -> 6 falls by 1 at each step, and 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…