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.
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)
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))
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)
We use pythontutor.com to illustrate a walk through of the countNodes function running on some sample trees.
Small example
Medium example