Range Sum of BST
TreesDFS
EasyLeetCode #938
Problem Statement
Given the `root` 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
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
Algorithm Explanation
We can solve this problem efficiently by leveraging the properties of a Binary Search Tree (BST). We'll perform a DFS traversal, but we can prune branches that are out of the given range.
Algorithm Steps
- DFS Traversal: We'll use a recursive DFS function that takes a node as input.
- Node in Range: If the current node's value is within the `[low, high]` range, we add its value to our running sum and recursively call on both its left and right children.
- Node too Low: If the current node's value is less than `low`, we know that all nodes in its left subtree will also be too low, so we only need to recursively call on its right child.
- Node too High: If the current node's value is greater than `high`, we know that all nodes in its right subtree will also be too high, so we only need to recursively call on its left child.
Start
Starting DFS from the root.
Total Sum: 0
Range Sum of BST Solution