Skip to content
RED SAGSkills

Sum of Prices in a Range

A binary tree is given as a level-order array: tree[0] is the root, then the children of each real node are listed left to right, level by level. A missing child is written as null, and the children of a missing node are not listed at all. For example [1,2,3,null,4] is root 1 with children 2 and 3, where 2 has only a right child 4.

A price index is stored as a binary search tree: every value in a left subtree is smaller than its node and every value in a right subtree is larger. All values are distinct.

Return the sum of all values v with low <= v <= high. Use the ordering to skip subtrees that cannot contain any value in the range.

Example 1

Input: tree = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: 7 + 10 + 15 = 32.

Example 2

Input: tree = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Explanation: 6 + 7 + 10 = 23.

Constraints

  • 0 <= number of nodes <= 10^4
  • -10^5 <= node value <= 10^5
  • low <= high
Hint 1

If a node is smaller than low, nothing in its left subtree can be in range.

Hint 2

Symmetrically, if a node is larger than high, skip its right subtree.

Good practice for: Backend Developer, Full Stack Developer, Data Engineer, Database Administrator, Site Reliability Engineer, Cloud Engineer

Run checks your code on 3 sample tests. Submit runs all 9 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.