Leetcode 938. Range Sum of BST
You are given the root
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:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: Nodes within range are [10, 7, 15]. Sum is 32.
low
and high
values always valid?
low <= high
.To solve this problem, leverage the properties of the Binary Search Tree:
[low, high]
, add it to the sum.low
, explore only the right subtree.high
, explore only the left subtree.#include <iostream>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if (!root) {
return 0; // Base case: if the node is null, return 0
}
// Initialize the sum
int sum = 0;
// Case 1: Node's value is within the range
if (root->val >= low && root->val <= high) {
sum += root->val;
}
// Case 2: Node's value is greater than low, explore left subtree
if (root->val > low) {
sum += rangeSumBST(root->left, low, high);
}
// Case 3: Node's value is less than high, explore right subtree
if (root->val < high) {
sum += rangeSumBST(root->right, low, high);
}
return sum;
}
};
// Helper function to create a new node
TreeNode* newNode(int data) {
TreeNode* node = new TreeNode();
node->val = data;
node->left = node->right = nullptr;
return node;
}
// Main function to test the solution
int main() {
// Creating the tree from the example
/* Tree:
10
/ \
5 15
/ \ \
3 7 18
*/
TreeNode* root = newNode(10);
root->left = newNode(5);
root->right = newNode(15);
root->left->left = newNode(3);
root->left->right = newNode(7);
root->right->right = newNode(18);
Solution sol;
int low = 7, high = 15;
std::cout << "Range Sum of BST (7, 15): " << sol.rangeSumBST(root, low, high) << std::endl; // Output: 32
return 0;
}
n
is the number of nodes in the BST. This is because we might end up visiting all nodes if all values fall within the range or if the tree is skewed.h
is the height of the tree due to the recursive stack. In the worst case, it is O(n) if the tree is completely unbalanced or skewed.This solution effectively leverages the BST properties to minimize unnecessary traversals, ensuring efficient computation of the range sum.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?