Problem 459319 · medium · Level 04 Non-Linear Data Structures

How Many Bids Fall Below the Reserve

binary search tree · pruning · counting

An auction's bids are stored in a binary search tree with distinct values. Given a reserve price x, return how many bids are strictly less than x. Never visit a subtree whose values are all at least x.

Examples

        46
       /  \
     28    63
    /  \     \
  15   37    84
    \
     24

Input:  root = build_tree([46, 28, 63, 15, 37, None, 84, None, 24]), x = 41
Output: 4        (15, 24, 28, 37)

Input:  root = build_tree([46, 28, 63, 15, 37, None, 84, None, 24]), x = 15
Output: 0

Constraints

  • 0 <= number of nodes <= 3000
  • All values are distinct integers
  • Visit only the qualifying nodes plus one search path

Goals

  • Count whole subtrees at once when they are known to qualify
  • Skip subtrees that cannot contain qualifying values
Starting Python…