FastPrepRange Sum of BST

Range Sum of BST

Meta logoMeta● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Given the root of a binary search tree and two integers low and high, return the sum of the values of every node whose value is in the inclusive range [low, high].

A node outside the range may still have descendants inside the range. Use the binary search tree ordering to skip subtrees only when it is safe.

Function

rangeSumBST(root: TreeNode, low: int, high: int) → int

Examples

Example 1

root = [10,5,15,3,7,null,18]low = 7high = 15return = 32

The values in the inclusive range are 7, 10, and 15. Their sum is 32.

Example 2

root = [10,5,15,3,7,13,18,1,null,6]low = 6high = 10return = 23

The qualifying values are 6, 7, and 10, which sum to 23.

Example 3

root = [8]low = 9high = 12return = 0

The only node is below the interval, so no value contributes to the sum.

Constraints

  • The tree contains between 1 and 20000 nodes.
  • Node values are unique integers between 1 and 100000.
  • 1 <= low <= high <= 100000.
  • The input satisfies the binary search tree ordering invariant.

More Meta problems

See Meta hiring insights
public int rangeSumBST(TreeNode root, int low, int high) {
    // Write your code here
}
root[10,5,15,3,7,null,18]
low7
high15
expected32
Checking account…