Course Home | Assignments | Data Sets/Tools | Python | Schedule | Git Submission | Tutoring

Recursion

For review, we rely on a tree representation that uses nesting of Python tuples. While that representation may quickly get unweildy for a human, it turns out that we can write algorithms that work with such a structure quite easily, by using the power of recursion to repeat processes on subtrees. We'll explore several examples of such recursive algorithms.

determining the total number of nodes in a tree

def countNodes(tree):
    """Return the total number of nodes in the given tree."""
    root,first,second = tree    # unpack the tuple
    if first == second == ():
        return 1     # this tree is itself a leaf
    else:
        return 1 + countNodes(first) + countNodes(second)

determining the maximum height of a tree

def height(tree):
    """Return the length of the longest branch of the tree."""
    root,first,second = tree    # unpack the tuple

    if first == second == ():
        return 0     # a leaf has height 0

    else:
        return 1 + max(height(first), height(second))

producing a list of labels for all of the leaves of a tree

def leafList(tree):
    """Return list of labels for the leaves of the tree."""
    root,first,second = tree    # unpack the tuple
    if first == second == ():
        return [ root ]       # tree with one node
    else:
        return leafList(first) + leafList(second)

Example Execution

We use pythontutor.com to illustrate a walk through of the countNodes function running on some sample trees.

Small example

Medium example


Michael Goldwasser
Last modified: Sunday, 03 March 2019
Course Home | Assignments | Data Sets/Tools | Python | Schedule | Git Submission | Tutoring