Range Sum of BST easy
Problem Statement
Given the root
node of a binary search tree (BST) 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
Steps and Explanation
The problem can be efficiently solved using a recursive approach that leverages the properties of a BST. Since a BST is ordered, we can prune our search significantly.
-
Recursive Function: We define a recursive function
rangeSumBST
that takes the root node,low
, andhigh
as input. -
Base Case: If the current node is
null
, we return 0 (no sum). -
Pruning:
- If the current node's value is less than
low
, we only need to recursively search the right subtree (since values in the left subtree will be even smaller). - If the current node's value is greater than
high
, we only need to recursively search the left subtree (since values in the right subtree will be even larger).
- If the current node's value is less than
-
Inclusion: If the current node's value is within the range
[low, high]
, we include its value in the sum and recursively search both the left and right subtrees. -
Return Value: The function returns the sum of the current node's value (if included) and the recursive sums from the left and right subtrees.
Code
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
if (root == null) {
return 0;
}
if (root.val < low) {
return rangeSumBST(root.right, low, high);
} else if (root.val > high) {
return rangeSumBST(root.left, low, high);
} else {
return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high);
}
}
}
Complexity
- Time Complexity: O(N) in the worst case, where N is the number of nodes in the BST. However, due to pruning, it's often significantly less than O(N) if the range
[low, high]
is small or strategically located within the tree. - Space Complexity: O(H) in the worst case, where H is the height of the BST. This is due to the recursive call stack. In a balanced BST, H is log(N), but in a skewed BST, H can be N.