Menu
CoddyTech

Range Sum of BST

You get a binary search tree stored in the array tree in level order, and two numbers low and high. The root sits at index 0, the children of the node at index i sit at 2*i+1 (left) and 2*i+2 (right), -1 marks an empty spot, and the array may end with extra -1 entries. In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger.

Write a function named rangeSumBST that returns the sum of all node values v with low ≤ v ≤ high, or 0 when no value is in that range.

Function

rangeSumBST(tree: integer-array, low: integer, high: integer) → integer
treeinteger-array
the binary search tree in level order, with -1 for an empty spot
lowinteger
the smallest value to count
highinteger
the largest value to count
Returnsinteger
the sum of the node values between low and high, both included

Constraints

  • 1 ≤ tree.length ≤ 32767
  • Each tree[i] is -1 or a value with 0 ≤ tree[i] ≤ 105.
  • tree[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the depth is at most 14.
  • The tree is a valid binary search tree, so all its values are distinct.
  • 0 ≤ low ≤ high ≤ 105
  • The answer fits in a 32-bit signed integer.

Examples

Input
tree = [20, 8, 31, 3, 12, -1, 40, -1, -1, 10, 15]low = 9high = 31
Output
88
Explanation
The values from 9 to 31 are 10, 12, 15, 20 and 31, which add up to 88. The 3, 8 and 40 fall outside the range.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

If you had to answer thousands of different (low, high) queries on the same tree, how could you answer each one in O(log n) time?

Reset code
def rangeSumBST(tree, low, high):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

tree = [20, 8, 31, 3, 12, -1, 40, -1, -1, 10, 15]
low = 9
high = 31

Expected

88