CS 61A

Structure and Interpretation of Computer Programs, Spring 2015

Instructor: John DeNero




Question | Count Branches

Define count_branches, which takes a non-rooted tree t, and returns the number of branches in t. You may assume is_leaf(tree) is defined for you.

def count_branches(t):
    """
    >>> t1 = [1, [2, 3], [3, [4, 3]]]
    >>> count_branches(t1)
    9
    >>> t2 = [2]
    >>> count_branches(t2)
    1
    """
    ## YOUR CODE HERE ##
def count_branches(tree):
    if is_leaf(tree):
        return 0
    new_tree = [count_branches(t) + 1 for t in tree]
    return sum(new_tree)