""" an example of a tree data structure and a recursive program to count the nodes in the tree. Jim Mahoney cs.marlboro.edu | GPL | Nov 2011 """ print """The tree looks like this: a / \\ b c /|\\ d e f """ # Quick quiz 1: W # Why are there \\ rather than \ characters in the print statement above? # Define each node as a dictionary, starting at the bottom. # (The nodes beneath a 'parent' are called 'children'.) f = {'name':'f', 'kids':[]} e = {'name':'e', 'kids':[]} d = {'name':'d', 'kids':[]} c = {'name':'c', 'kids':[d, e, f]} b = {'name':'b', 'kids':[]} a = {'name':'a', 'kids':[b, c]} # Here's what it looks like as a single python data structure. import pprint pp = pprint.PrettyPrinter() print "Here's how it looks as a data structure:" pp.pprint(a) # Now the recursive function. # Quick quiz 2 : why this doesn't recur forever? def count_tree_nodes(node): """Return number of nodes at and below this one""" count = 1 for child in node['kids']: count = count + count_nodes(child) return count print "The number of nodes in the tree is %i." % count_tree_nodes(a) # Quick quiz 3: # What would happen if we tried to use this on a graph? # # (Graphs can have loops, in which the 'lower' ones # connect back to 'higer' ones.) # # Not-as-quick quiz 4: # How could you define a graph in a python structure? # # Even-longer quiz 5: # Could the count_tree_nodes function be # adopted to work on graphs?