938. Range Sum of BST

938. Range Sum of BST

Problem Solving - Day 67

ยท

3 min read

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 integers low and high, 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 and high, 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 and high 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 and high in the right subtree
    • 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 and high in the left subtree
    • the value at root node falls between low and high.

      • We include this value for the sum and try to recursively search in both left and right subtrees.

Illustration_solution

๐Ÿ‘ฉ๐Ÿฝโ€๐Ÿ’ป Solution - Traverse List

  • Below is the code for the approach using getting the length and returning length/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


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!