The code from the chapter is presented here, following the convention that a list represents a hierachical tree with the first item of the list being the "name" of the tree and remaining items being either leaves or (recursively) subtrees in the hierarchy. (A couple of print statements are added to aid in understanding the processing order when it runs.)


Recursion in Named Tree

def leafCount(Tree):
  if type(Tree) != list:
     print "At leaf", Tree
     return 1
  else:
     print "Tree Name", Tree[0]
     return sum( leafCount(i) for i in Tree[1:] )
r = leafCount([1,2,[3,4],[5,[6,7]]])


A streamlined rewriting of the code is to ignore names, and just consider anything in a list to be either a leaf or another subtree. Then we have:


Recursive Leaf Counting

def leafCount(Tree):
  if type(Tree) != list:
     print "Leaf", Tree
     return 1
  else:
     return sum( leafCount(i) for i in Tree )
r = leafCount([1,2,[3,4],[5,[6,7]]])