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

Answer Several Age-Bracket Counts

binary search tree · pruning · queries

A club stores members' ages in a binary search tree with distinct values. You receive a list of queries, each a pair [lo, hi]. For every query, count the ages a with lo <= a <= hi. Return the counts in query order.

Examples

         12
        /  \
       7    18
      / \   / \
     3   9 15  22
      \
       5

Input:  root = build_tree([12, 7, 18, 3, 9, 15, 22, None, 5]),
        queries = [[4, 12], [16, 30], [100, 200]]
Output: [4, 2, 0]
Explanation: 5, 7, 9, 12 lie in 4..12; 18, 22 lie in 16..30; nothing is in 100..200.

Constraints

  • 0 <= number of nodes <= 3000, 0 <= len(queries) <= 50
  • All values are distinct integers; lo <= hi in every query
  • Each query should skip subtrees that lie completely outside its bracket

Goals

  • Count values in an inclusive range without scanning out-of-range subtrees
  • Answer a list of queries with one helper
Starting Python…