Range Sum of BST
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) → intExamples
Example 1
root = [10,5,15,3,7,null,18]low = 7high = 15return = 32The 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 = 23The qualifying values are 6, 7, and 10, which sum to 23.
Example 3
root = [8]low = 9high = 12return = 0The only node is below the interval, so no value contributes to the sum.
Constraints
- The tree contains between
1and20000nodes. - Node values are unique integers between
1and100000. 1 <= low <= high <= 100000.- The input satisfies the binary search tree ordering invariant.