Skip to content

Commit 43ea492

Browse files
938. Range Sum of BST
Difficulty: Easy 42 / 42 test cases passed. Runtime: 316 ms Memory Usage: 21.7 MB
1 parent 1fe2a05 commit 43ea492

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Easy/938.RangeSumofBST.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
Given the root node of a binary search tree, return the sum of values of
3+
all nodes with value between L and R (inclusive).
4+
The binary search tree is guaranteed to have unique values.
5+
6+
Example:
7+
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
8+
Output: 32
9+
10+
Note:
11+
1. The number of nodes in the tree is at most 10000.
12+
2. The final answer is guaranteed to be less than 2^31.
13+
"""
14+
#Difficulty: Easy
15+
#42 / 42 test cases passed.
16+
#Runtime: 316 ms
17+
#Memory Usage: 21.7 MB
18+
19+
#Runtime: 316 ms, faster than 20.89% of Python3 online submissions for Range Sum of BST.
20+
#Memory Usage: 21.7 MB, less than 94.93% of Python3 online submissions for Range Sum of BST.
21+
22+
class Solution:
23+
def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
24+
summ = 0
25+
if not root:
26+
return 0
27+
if L <= root.val <= R:
28+
summ += root.val
29+
summ += self.rangeSumBST(root.left, L, R)
30+
summ += self.rangeSumBST(root.right, L, R)
31+
return summ

0 commit comments

Comments
 (0)