A company stores staff badge numbers (distinct integers) in a binary search tree. Every node is a manager whose department is the manager together with everybody in their subtree.
You receive queries, a list of pairs (x, k). For each, find the k-th smallest badge
number in the department of the manager with badge x (k = 1 is the smallest). If that
department has fewer than k people, the answer is -1. Return the answers as a list, in query
order.
One test calls balanced_tree(n), which builds a height-balanced search tree holding
0, 1, ..., n - 1.
Examples
64
/ \
31 88
/ \ / \
17 49 72 95
/ \
42 56
Input: root = build_tree([64, 31, 88, 17, 49, 72, 95, None, None, 42, 56]),
queries = [(31, 3), (88, 1), (31, 6), (64, 7)]
Output: [42, 72, -1, 72]
Explanation: 31's department is 17, 31, 42, 49, 56; its 3rd smallest is 42 and it has no 6th.
Input: same tree, queries = [(56, 1), (49, 2)]
Output: [56, 49]
Constraints
1 <= number of nodes <= 2 * 10**4; the tree may be one long path0 <= len(queries) <= 2 * 10**4; everyxis a badge in the tree;1 <= k <= 10**5- Walking a department once per query is far too slow for the largest tests.
Goals
- See that a subtree's values form one contiguous block of the sorted order
- Locate that block from a node's inorder position and its left subtree size
- Answer many queries after one linear preprocessing pass