Leetcode 938. Range Sum of BST
You are given the root of a Binary Search Tree (BST) and two integers low
and high
. You need to return the sum of values of all nodes with a value in the inclusive range [low, high]
.
low
and high
?
[low, high]
, add its value to the sum.low
, there might be nodes in the left subtree within the range, so explore the left subtree.high
, there might be nodes in the right subtree within the range, so explore the right subtree.null
, return 0 since it does not contribute to the sum./**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int low, int high) {
// If the current node is null, return 0 as there's no value to add
if (root == null) {
return 0;
}
// Initialize the sum to 0
int sum = 0;
// If the current node's value is within the range, add it to the sum
if (root.val >= low && root.val <= high) {
sum += root.val;
}
// If the current node's value is greater than low, check the left subtree
if (root.val > low) {
sum += rangeSumBST(root.left, low, high);
}
// If the current node's value is less than high, check the right subtree
if (root.val < high) {
sum += rangeSumBST(root.right, low, high);
}
// Return the computed sum
return sum;
}
}
O(N)
, where N
is the number of nodes in the BST. In the worst case, we may need to visit all nodes.O(H)
, where H
is the height of the BST. This accounts for the recursive call stack, which in the worst case of an unbalanced tree could be O(N)
(typically O(log N)
for balanced trees).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?