LeetCode · March 28, 2021

Range Sum of BST | LeetCode 938 | Python | Solution

Click here to see the problem on LeetCode.

A simple Tree related problem and description is pretty straightforward.

We have to return the sum of values of all nodes with a value in the range. The range is actually a minimum integer and a maximum integer. If a node value is in the range, we will count it. Otherwise not.

To do that, we have to traverse all nodes using any of the traversing algorithms. This time we will use the preorder traversal algorithm. By this algorithm, we will check each node’s value when we traverse through the given tree.

Let’s see the code example.

class Solution:
    def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
        
        result = 0
        
        if root is None:
            return result
        
        stack = [root]
        
        while stack:
            curr = stack.pop()
            
            if curr.val >= L and curr.val <= R:
                result += curr.val
            
            if curr.left:
                stack.append(curr.left)
            if curr.right:
                stack.append(curr.right)
        
        return result