Hello, reader ๐๐ฝ ! Welcome to day 67 of the series on Problem Solving. Through this series, I aim to pick up at least one question everyday and share my approach for solving it.
Today, I will be picking up LeetCode's daily challenge problem: 938. Range Sum of BST.
๐ค Problem Statement
Given the
root
node of a binary search tree and two integerslow
andhigh
, return the sum of values of all nodes with a value in the inclusive range[low, high]
.E.g:
root = [10,5,15,3,7,null,18], low = 7, high = 15
=>32
root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
=>23
๐ฌ Thought Process - Tree Traversal
We can use the property of a BST to solve this problem. Since we have two values
low
andhigh
, we can compare the current root value with these values and decide if we can decrease the search space or not.At every node, we compare the current value with the given
low
andhigh
values.We would have three different cases:
the value at root node is less than
low
=>root.val < low
- We eliminate the left subtree and search for nodes that fall within
low
andhigh
in the right subtree
- We eliminate the left subtree and search for nodes that fall within
the value at root node is greater than
high
=>root.val > high
- We eliminate the right subtree and search for nodes that fall within
low
andhigh
in the left subtree
- We eliminate the right subtree and search for nodes that fall within
the value at root node falls between
low
andhigh
.- We include this value for the sum and try to recursively search in both left and right subtrees.
๐ฉ๐ฝโ๐ป Solution - Traverse List
- Below is the code for the approach using getting the
length
and returninglength/2
element.
/**
* 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;
int val = root.val;
if(val < low) {
return rangeSumBST(root.right, low, high);
}
else if(val > high) {
return rangeSumBST(root.left, low, high);
}
return val +
rangeSumBST(root.left, low, high) +
rangeSumBST(root.right, low, high);
}
}
Time Complexity: O(n)
- n = number of nodes in the tree
Space Complexity: O(h)
- h = height of the tree. In the worst case h == n
- You can find the link to the GitHub repo for this question here: 938. Range Sum of BST.
Conclusion
That's a wrap for today's problem. If you liked my explanation then please do drop a like/ comment. Also, please correct me if I've made any mistakes or if you want me to improve something!
Thank you for reading!