forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_258.py
51 lines (38 loc) · 986 Bytes
/
problem_258.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
class Node:
def __init__(self, val):
self.val = val
self.ln = None
self.rn = None
def __repr__(self):
return "Node=({}, ln={}, rn={})".format(
self.val, self.ln, self.rn)
def get_bfs_alt(root, level, level_dict):
if not root:
return
if level not in level_dict:
level_dict[level] = list()
level_dict[level].append(root.val)
get_bfs_alt(root.ln, level + 1, level_dict)
get_bfs_alt(root.rn, level + 1, level_dict)
def get_boustrophedon(root):
level_dict = dict()
get_bfs_alt(root, 0, level_dict)
final_order = list()
for i in range(len(level_dict)):
final_order.extend(reversed(level_dict[i]) if i % 2 else level_dict[i])
return final_order
# Tests
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)
n6 = Node(6)
n7 = Node(7)
n2.ln = n4
n2.rn = n5
n3.ln = n6
n3.rn = n7
n1.ln = n2
n1.rn = n3
assert get_boustrophedon(n1) == [1, 3, 2, 4, 5, 6, 7]