-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path938_Range_Sum_of_BST.py
More file actions
71 lines (61 loc) · 1.92 KB
/
938_Range_Sum_of_BST.py
File metadata and controls
71 lines (61 loc) · 1.92 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
# Time: O(N), Space: O(N)
# Iterative/Brute Force
# def rangeSumBST(self, root, low, high):
# """
# :type root: TreeNode
# :type low: int
# :type high: int
# :rtype: int
# """
# if not root:
# return 0
# answer = 0
# if root.val >= low and root.val <= high:
# answer += root.val
# answer += self.rangeSumBST(root.left, low, high)
# answer += self.rangeSumBST(root.right, low, high)
# return answer
# Time: O(), Space: O(N)
# Interative
# DFS
def rangeSumBST(self, root, low, high):
"""
:type root: TreeNode
:type low: int
:type high: int
:rtype: int
"""
stack = [root]
answer = 0
while stack:
currentNode = stack.pop()
if currentNode:
if currentNode.val >= low and currentNode.val <= high:
answer += currentNode.val
if currentNode.val > low:
stack.append(currentNode.left)
if currentNode.val < high:
stack.append(currentNode.right)
return answer
# # Time: O(N), Space: O(N)
# # Recursursion
# def rangeSumBST(self, root, low, high):
# self.answer = 0
# def dfs(currentNode):
# if currentNode:
# return
# if low <= currentNode.val <= high:
# self.answer += currentNode.val
# if low <= currentNode.val:
# dfs(currentNode.left)
# if currentNode.val <= high:
# dfs(currentNode.high)
# dfs(root)
# return self.answer