-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathRange Sum of BST.py
46 lines (34 loc) · 1.02 KB
/
Range Sum of BST.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if root is None:
return 0
return self.rangeSumBST(root.left, low, high) + \
self.rangeSumBST(root.right, low, high) + \
root.val * (low <= root.val <= high)
class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
queue = [root]
range_sum = 0
while queue:
node = queue.pop()
if low <= node.val <= high:
range_sum += node.val
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
return range_sum