Binary Search Trees BST basics
385. Range Sum of BST
You are given root, the root node of a binary search tree, and two integers low and high. Return the
sum of the values of all nodes whose value lies between low and high, both included. If no value lies in
that range, return 0.
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. The values in the tree are distinct.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [20, 9, 34, 4, 13, 27, 50, null, 6, 11, null, null, 30]
low = 11
high = 30
101Explanation: The nodes 11, 13, 20, 27 and 30 lie in the range, and 11 + 13 + 20 + 27 + 30 = 101. The values 11 and 30 sit exactly on the bounds, and they count.
Example 2
Input: root = [-5, -12, 8, null, -7, 3]
low = -10
high = 2
-12Explanation: Only -7 and -5 lie in the range, so the sum is -12. The value -12 is below low, and 3 and 8 are above
high.
Example 3
Input: root = [999999999, 999999998, 1000000000, 999999997]
low = -1000000000
high = 1000000000
3999999994Explanation: Every node lies in the range, so the answer is the sum of all four values.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
- The tree is a binary search tree, and its values are distinct.
-109 ≤ low ≤ high ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.