Problem · Tree
Repeated BST Range Sum and Average
Learn this problemProblem statement
Given a binary search tree with unique integer keys and an ordered batch of inclusive range queries, preprocess the tree and answer every query.
For each query [low, high], return one row [sum, average]:
sumis the sum of all keysxsatisfyinglow <= x <= high.averageis their arithmetic mean.- When the range contains no key, return
[0.0, 0.0].
Return the rows in query order. Both values use double in the runner output.
Function
rangeAggregates(root: TreeNode, queries: int[][]) → double[][]Examples
Example 1
root = [10,5,15,3,7,null,18]queries = [[7,15],[6,10],[16,17]]return = [[32.0,10.666666666666666],[17.0,8.5],[0.0,0.0]]The first range contains 7, 10, and 15. The second contains 7 and 10. The third is empty.
Example 2
root = [4,2,6,1,3,5,7]queries = [[1,7],[4,4],[8,9]]return = [[28.0,4.0],[4.0,4.0],[0.0,0.0]]The full range contains all seven keys, the single-point range contains only 4, and the last range contains none.
Example 3
root = []queries = [[-5,5]]return = [[0.0,0.0]]An empty tree contributes no values to any range.
Constraints
- The tree contains from
0through200000nodes. - Every key is unique and lies between
-10^9and10^9, inclusive. - The input satisfies the binary search tree ordering invariant.
1 <= queries.length <= 200000.- Every query satisfies
-10^9 <= low <= high <= 10^9. - Every range sum fits a signed 64-bit integer.