-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0938-range-sum-of-bst.py
More file actions
39 lines (30 loc) · 908 Bytes
/
0938-range-sum-of-bst.py
File metadata and controls
39 lines (30 loc) · 908 Bytes
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
# time complexity: O(n)
# space complexity: O(n)
# Definition for a binary tree node.
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:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
SumBST = 0
def preorder(node: Optional[TreeNode]):
nonlocal SumBST
if node:
if low <= node.val <= high:
SumBST += node.val
preorder(node.left)
preorder(node.right)
preorder(root)
return SumBST
root = TreeNode(10)
root.left = TreeNode(5)
root.left.left = TreeNode(3)
root.left.right = TreeNode(7)
root.right = TreeNode(15)
root.right.right = TreeNode(18)
low = 7
high = 15
print(Solution().rangeSumBST(root, low, high))