-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path938.py
30 lines (27 loc) · 818 Bytes
/
938.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
# [ LeetCode ] 938. Range Sum of BST
class TreeNode:
def __init__(
self,
val: int = 0,
left: "TreeNode" = None,
right: "TreeNode" = None
):
self.val = val
self.left = left
self.right = right
def solution(root: TreeNode, low: int, high: int) -> int:
answer: int = 0
stack: list[TreeNode] = [root]
while stack:
node: TreeNode = stack.pop()
if node.val > high and node.left:
stack.append(node.left)
elif node.val < low and node.right:
stack.append(node.right)
elif node.val >= low and node.val <= high:
answer += node.val
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return answer