Range Sum of BST

Problem Id: 938 Difficulty: Easy Tag: Tree Tag: Recursion


Intuition

Recursivly get the nodes between L and R and get the sum of these nodes.

Solution


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
        if root is None:
            return 0
        if L <= root.val <= R:
            return self.rangeSumBST(root.left, L, R) + \
                    self.rangeSumBST(root.right, L, R) + root.val
        elif root.val < L:
            return self.rangeSumBST(root.right, L, R)
        else:
            return self.rangeSumBST(root.left, L, R)