LeetCode 938: Range Sum of BST Solution
Master LeetCode problem 938 (Range Sum of BST), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
938. Range Sum of BST
Problem Explanation
Explanation
To solve this problem, we can perform a depth-first search (DFS) traversal of the binary search tree (BST). At each node, we check if the node's value falls within the range [low, high]. If it does, we add the node's value to the sum. We then recursively traverse the left and right subtrees if they exist.
Algorithm:
- Initialize a variable
sumto store the total sum. - Perform a recursive DFS traversal starting from the root node.
- At each node:
- If the node's value is within the range [low, high], add the value to the
sum. - Recursively traverse the left and right subtrees if they exist.
- If the node's value is within the range [low, high], add the value to the
- Return the final
sumvalue.
Time Complexity:
The time complexity of this algorithm is O(N), where N is the number of nodes in the binary search tree. We visit each node once in the worst case.
Space Complexity:
The space complexity is O(H), where H is the height of the binary search tree. In the worst case, the recursion stack can go as deep as the height of the tree.
Solution Code
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
if (root == null) {
return 0;
}
int sum = 0;
if (root.val >= low && root.val <= high) {
sum += root.val;
}
sum += rangeSumBST(root.left, low, high);
sum += rangeSumBST(root.right, low, high);
return sum;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 938 (Range Sum of BST)?
This page provides optimized solutions for LeetCode problem 938 (Range Sum of BST) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 938 (Range Sum of BST)?
The time complexity for LeetCode 938 (Range Sum of BST) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 938 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 938 in Java, C++, or Python.