Range Sum of BST

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

30:00

Range Sum of BST
easy
Free written solution
Topics
Companies

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

Example 1:
Input: {"root":[10,5,15,3,7,null,18],"low":7,"high":15}
Output: 32
Constraints:
  • The number of nodes in the tree is in the range [1,2×104][1, 2 \times 10^4].

  • 1≤Node.val≤1051 \leq \text{Node.val} \leq 10^5

  • 1≤low≤high≤1051 \leq \text{low} \leq \text{high} \leq 10^5

  • All Node.val are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[10,5,15,3,7,null,18],"low":7,"high":15}

Sum every value in [7, 15]. Sorted left to right, the in-range values form one band of columns.

low=7high=15105153718

stack (top first)

empty

total =

0

popped node
in range, added
visited, out of range
on stack
skipped subtree
Columns are sorted by value, so the blue band holds exactly the values in [low, high].
Variables
VariableValue
low7
high15
nodenull
total0
stack[]
DepthFunction Call
Stack empty
0/15