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

        5
       / \
      4   9
     /   / \
    6   10  2
   /      \
  7        11

Input:  root = build_tree([5, 4, 9, 6, None, 10, 2, 7, None, None, 11])
Output: 3
Explanation: 9 -> 10 -> 11; 5 -> 4 goes down by one and 4 -> 6 jumps by two, so neither extends a run.

Input:  root = build_tree([7, 6, 8, 7, None, 7])
Output: 2
Explanation: 7 -> 8 and 6 -> 7 are runs of two; 6, 7, 8 would have to climb back up through the root, and 8 -> 7 goes down by one.

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…