Skip to content

Commit 78c16c3

Browse files
authored
Create range-sum-of-bst.py
1 parent 02bc8fb commit 78c16c3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Python/range-sum-of-bst.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Definition for a binary tree node.
5+
class TreeNode(object):
6+
def __init__(self, x):
7+
self.val = x
8+
self.left = None
9+
self.right = None
10+
11+
12+
class Solution(object):
13+
def rangeSumBST(self, root, L, R):
14+
"""
15+
:type root: TreeNode
16+
:type L: int
17+
:type R: int
18+
:rtype: int
19+
"""
20+
result = 0
21+
s = [root]
22+
while s:
23+
node = s.pop()
24+
if node:
25+
if L <= node.val <= R:
26+
result += node.val
27+
if L < node.val:
28+
s.append(node.left)
29+
if node.val < R:
30+
s.append(node.right)
31+
return result

0 commit comments

Comments
 (0)