Algorithm
Problem Name: 938. Range Sum of BST
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 * 104]
. 1 <= Node.val <= 105
1 <= low <= high <= 105
- All
Node.val
are unique.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
return !root ? 0 :
root->val < L ? rangeSumBST(root->right, L, R) :
root->val > R ? rangeSumBST(root->left, L, R) : root->val + rangeSumBST(root->right, L, R) + rangeSumBST(root->left, L, R);
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
int sum = 0;
Queue < TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode removed = queue.remove();
if (removed.val >= low && removed.val < = high) {
sum += removed.val;
}
if (removed.val >= low && removed.left != null) {
queue.add(removed.left);
}
if (removed.val < = high && removed.right != null) {
queue.add(removed.right);
}
}
return sum;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Javascript Programming
Code -
Javascript Programming
const rangeSumBST = function(root, L, R) {
const payload = {sum: 0}
traverse(root, payload, L, R)
return payload.sum
};
function traverse(node, obj, L, R) {
if(node == null) return
if(node.val >= L && node.val <= R) obj.sum += node.val
traverse(node.left, obj, L, R)
traverse(node.right, obj, L, R>
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Python Programming
Code -
Python Programming
class Solution:
def rangeSumBST(self, root, L, R):
if not root: return 0
l = self.rangeSumBST(root.left, L, R)
r = self.rangeSumBST(root.right, L, R)
return l + r + (L <= root.val <= R) * root.val
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0938_RangeSumOfBST
{
public int RangeSumBST(TreeNode root, int L, int R)
{
if (root == null)
return 0;
else if (root.val < L)
return RangeSumBST(root.right, L, R);
else if (root.val > R)
return RangeSumBST(root.left, L, R);
else
return root.val + RangeSumBST(root.left, L, R) + RangeSumBST(root.right, L, R);
}
}
}
Copy The Code &
Try With Live Editor
Input
Output