-
Notifications
You must be signed in to change notification settings - Fork 4
/
sumDiagonals.py
71 lines (59 loc) · 1.74 KB
/
sumDiagonals.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
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
from Tree.commons import insert, Node, print_tree
from queue import Queue
def diagonals_sum_recursive(root, d=0):
if root is None:
return
if d in diagonals_sum_recursive.hm:
diagonals_sum_recursive.hm[d].append(root.key)
else:
diagonals_sum_recursive.hm[d] = [root.key]
diagonals_sum_recursive(root.left, d + 1)
diagonals_sum_recursive(root.right, d)
# https://www.youtube.com/watch?v=I3BC8nEKYm8
# https://www.geeksforgeeks.org/diagonal-sum-binary-tree/
def diagonals_sum_iterative(root):
q = Queue()
q.put(root)
q.put(None)
sum = 0
while not q.empty():
pnode = q.get()
if pnode is None:
# A delimiter `None` is used to mark the starting of next diagonal.
# Diagonal is complete, print sum.
print(sum)
sum = 0
q.put(None)
pnode = q.get()
while pnode is not None:
sum += pnode.key
if pnode.left is not None:
q.put(pnode.left)
pnode = pnode.right
if __name__ == '__main__':
"""
50
/ \
30 70
/ \ / \
20 40 60 80
/ \
15 25
"""
root = None
root = insert(root, 50)
insert(root, 30)
insert(root, 20)
insert(root, 15)
insert(root, 25)
insert(root, 40)
insert(root, 70)
insert(root, 60)
insert(root, 80)
print("\n------------------ Using recursive approach ------------------\n")
diagonals_sum_recursive.hm = {}
diagonals_sum_recursive(root)
for k,v in diagonals_sum_recursive.hm.items():
print(sum(v))
print("\n------------------ Using iterative approach ------------------\n")
diagonals_sum_iterative(root)