link: Range Sum of BST
Thought
When first saw this question, I think using tree traverse could solve it and it did works.
Code
# 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, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
self.res = 0
def helper(root): # helper function to traverse tree
if not root:
return
if L <= root.val <= R:
self.res += root.val
helper(root.left)
helper(root.right)
elif root.val < L:
helper(root.right)
else:
helper(root.left)
helper(root)
return self.res
Runtime
Time O(n)
Space O(n)