Problem 4: Fold Tree (0pts)
It is often the case that we want to fold a tree into a value. Consider the following implementations of count_leaves
and label_sum
.
def count_leaves(t):
"""Count the leaves of a tree."""
if is_leaf(t):
return 1
return sum([count_leaves(b) for b in branches(t)])
def label_sum(t):
"""Sum up the labels of all nodes in a tree."""
if is_leaf(t):
return label(t)
return label(t) + sum([label_sum(b) for b in branches(t)])
The implementations look quite similar! Now, it is time to define a function fold_tree
to abstract such a process.
def fold_tree(t, base_func, merge_func):
"""Fold tree into a value according to base_func and merge_func"""
"*** YOUR CODE HERE ***"
You can feel free to define the meaning and usage of base_func
and merge_func
. Then use fold_tree
to implement count_leaves
, label_sum
and preorder
.
def count_leaves(t):
"""Count the leaves of a tree.
>>> t = tree(1, [tree(2), tree(3, [tree(4), tree(5)])])
>>> count_leaves(t)
3
"""
return fold_tree(t, 'YOUR EXPRESSION HERE', 'YOUR EXPRESSION HERE')
def label_sum(t):
"""Sum up the labels of all nodes in a tree.
>>> t = tree(1, [tree(2), tree(3, [tree(4), tree(5)])])
>>> label_sum(t)
15
"""
return fold_tree(t, 'YOUR EXPRESSION HERE', 'YOUR EXPRESSION HERE')
def preorder(t):
"""Return a list of the entries in this tree in the order that they
would be visited by a preorder traversal.
>>> t = tree(1, [tree(2), tree(3, [tree(4), tree(5)])])
>>> preorder(t)
[1, 2, 3, 4, 5]
"""
return fold_tree(t, 'YOUR EXPRESSION HERE', 'YOUR EXPRESSION HERE')