CS 61A

Structure and Interpretation of Computer Programs, Fall 2014

Instructor: John DeNero




Question | Replace with Leaf

Define replace_with_leaf, which takes a non-rooted tree tree and a number n, and returns a new tree where every leaf value of treeequal to n has been replaced with the word leaf.

def replace_with_leaf(tree, n):
    """
    >>> t1 = [1, [2, 3], [3, [4, 3]]]
    >>> replace_with_leaf(t1, 3)
    [1, [2, 'leaf'], ['leaf', [4, 'leaf']]]
    >>> replace_with_leaf(t1, 4)
    [1, [2, 3], [3, ['leaf', 3]]]
    """
    ## YOUR CODE HERE ##
def replace_with_leaf(tree, n):
    if is_leaf(tree):
        if tree == n:
            return "leaf"
        return tree
    else:
        new_tree = [replace_with_leaf(t, n) for t in tree]
        return new_tree