Leetcode 938: Range Sum of BST

Calculating the sum of all nodes in a given range by traversing a Binary Search Tree.

The original problem is here.

In-order traversal approach

Depth-First Search (DFS) Approach

Algorithm

My Solution

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        if root is None:
            return 0
        if (root.val < low):
            left_sum = 0
        else:
            left_sum = self.rangeSumBST(root.left, low, high)
        if (root.val > high):
            right_sum = 0
        else:
            right_sum = self.rangeSumBST(root.right, low, high)
        if (root.val < low) or (root.val > high):
            myself = 0
        else:
            myself = root.val

        return myself + left_sum + right_sum 
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        if not root:
            return 0
            
        # If the value is strictly less than low, skip the left subtree
        if root.val < low:
            return self.rangeSumBST(root.right, low, high)
            
        # If the value is strictly greater than high, skip the right subtree
        if root.val > high:
            return self.rangeSumBST(root.left, low, high)
            
        # If it is in range, include the node and check both subtrees
        return root.val + \
               self.rangeSumBST(root.left, low, high) + \
               self.rangeSumBST(root.right, low, high)

Complexity Analysis

References