"""
Solutions for Unofficial Quiz 5
issued on October 2, 2015
@author: Alvin Wan
@site: alvinwan.com
"""
tree = lambda val, branches=[]: (val, branches)
root = lambda t: t[0]
branches = lambda t: t[1]
is_tree = lambda t: isinstance(t, tuple)
def print_by_level(t):
"""
>>> t = tree(1, [tree(3, [tree(2), tree(4)]), tree(6, [tree(5), tree(7)])])
>>> print_by_level(t)
[1]
[3, 6]
[2, 4, 5, 7]
"""
lst, nxt, curr = [t], [], []
while lst:
for t in lst:
nxt += branches(t)
curr.append(root(t))
print(curr)
lst, nxt, curr = nxt, [], []
def print_level_order(t):
"""
>>> t = tree(1, [tree(3, [tree(2), tree(4)]), tree(6, [tree(5), tree(7)])])
>>> print_level_order(t)
1
3
2
4
6
5
7
"""
def helper(t):
children = branches(t)
print(root(t))
[helper(b) for b in children]
helper(t)
def print_reverse_level_order(t):
"""
>>> t = tree(1, [tree(3, [tree(2), tree(4)]), tree(6, [tree(5), tree(7)])])
>>> print_reverse_level_order(t)
7
5
6
4
2
3
1
"""
def helper(t):
children = branches(t)
[helper(b) for b in children[::-1]]
print(root(t))
helper(t)
def print_reverse_by_level(t):
"""
>>> t = tree(1, [tree(3, [tree(2), tree(4)]), tree(6, [tree(5), tree(7)])])
>>> print_reverse_by_level(t)
[2, 4, 5, 7]
[3, 6]
[1]
"""
def helper(lst, nxt, curr):
if lst:
for t in lst:
nxt += branches(t)
curr.append(root(t))
helper(nxt, [], [])
print(curr)
helper([t], [], [])