Range Sum Of BST Problem
Description
LeetCode Problem 938.
Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
Constraints:
- The number of nodes in the tree is in the range [1, 2 * 10^4].
- 1 <= Node.val <= 10^5
- 1 <= low <= high <= 10^5
- All Node.val are unique.
Solution
Approach: DFS That Skips Subtrees Outside the Range
Adding up every node works, but the BST property lets us skip whole subtrees that cannot contain an answer.
In a BST, everything in the left subtree of a node is smaller than the node, and everything in the right subtree is larger. At each node:
- If
root.val < low, the node is too small, and so is its entire left subtree. Only the right subtree can hold values in the range. - If
root.val > high, the node is too large, and so is its entire right subtree. Only the left subtree matters. - Otherwise the node is in
[low, high]: count its value and search both subtrees, since each may still contain values in the range.
An empty subtree contributes 0.
The detail to get right is that a node outside the range does not end the search: a node with value 3 and low = 7 can still have 10 in its right subtree. The function skips the node's value but continues on the one side that can still match.
For root = [10,5,15,3,7,null,18], low = 7, high = 15: at 5 (too small) we go only right to 7; at 15 we count it and its child 18 is skipped as too large. The sum is 10 + 7 + 15 = 32.
Complexity: O(n) time in the worst case, where n is the number of nodes (fewer nodes are visited when the range is narrow), and O(h) space for the recursion, where h is the height of the tree.
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if root is None:
return 0
if root.val < low:
# root and its whole left subtree are below the range
return self.rangeSumBST(root.right, low, high)
if root.val > high:
# root and its whole right subtree are above the range
return self.rangeSumBST(root.left, low, high)
return (root.val
+ self.rangeSumBST(root.left, low, high)
+ self.rangeSumBST(root.right, low, high))
Now write it from memory
Close the write-up and solve it yourself against the tests.