forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrange_sum.py
More file actions
34 lines (26 loc) · 674 Bytes
/
range_sum.py
File metadata and controls
34 lines (26 loc) · 674 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
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def range_sum_preorder(root, L, R):
stack = [root]
sum = 0
while stack:
node = stack.pop()
if node:
if L <= node.val <= R:
sum += node.val
if L < node.val:
stack.append(node.left)
if node.val < R:
stack.append(node.right)
return sum
root = Node(5)
root.left = Node(3)
root.right = Node(7)
root.left.left = Node(1)
root.left.right = Node(4)
root.right.right = Node(10)
root.right.left = Node(6)
print(range_sum_preorder(root, 7, 10))