Leetcode 975 Solution

This article provides solution to leetcode question 975 (range-sum-of-bst)

https://leetcode.com/problems/range-sum-of-bst

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

        ans = root.val if L <= root.val <= R else 0
        if root.val > L:
            ans += self.rangeSumBST(root.left, L, R)
        if root.val < R:
            ans += self.rangeSumBST(root.right, L, R)
        return ans