Structural Recursion
Example: Counting stock in a tree
A warehouse stores section records in a binary tree. You can total its stock using structural recursion: handle each possible form of the data, recursively process its immediate smaller components, and combine their results.
Example: Each record has a boxes field and two child links, left and right. An empty subtree is represented by None. The tree below is finite, has no cycles or shared nodes, and stores each section's own box count rather than a subtotal.
a) Complete the function so it returns the total number of boxes in any tree with this representation. Explain why its recursive calls eventually stop.
def total_boxes(node):
if node is None:
return EMPTY_TOTAL
return node.boxes + LEFT_TOTAL + RIGHT_TOTALA base case is a data form whose result can be returned without another recursive call. Here the empty subtree contains no boxes, so its total is zero.
For a nonempty subtree, combine the current section's boxes with the totals of its immediate left and right child subtrees:
The completed function is
def total_boxes(node):
if node is None:
return 0
return (node.boxes
+ total_boxes(node.left)
+ total_boxes(node.right))Each recursive call receives a child subtree with fewer nonempty records than the current subtree. Because the tree is finite and has no cycles, repeatedly following children eventually reaches None. A section with zero boxes would still require processing its children; the stopping condition depends on the structure, not the stored box count.
b) Trace the completed function on the pictured tree and find the warehouse's total stock.
Start with the bottom sections. Each has two empty children, whose returned totals are zero. The section storing 2 boxes therefore returns 2+0+0=2 boxes, and the section storing 1 box returns 1+0+0=1 box.
The subtree rooted at the 4-box section returns ________, because
The subtree rooted at the 3-box section returns ________, because
Finally, the root combines its own stock with both returned totals:
The warehouse contains 16 boxes. Adding the five displayed counts directly gives the same result, which checks that no section was skipped or counted twice.
c) How many times is total_boxes invoked? Include the initial call and all calls on None.
There are ________ nonempty records, so five invocations process section records. Every nonempty record makes two child calls, including calls for missing children.
Count those missing children from the picture: the 4-box and 3-box sections each have one, and the 2-box and 1-box sections each have two. The root has none. Thus the number of empty-child invocations is ________, obtained from
Adding the two kinds of invocation gives
There are 11 invocations in total. The five stored values determine the box total, while the tree's records and missing child links determine this call count.
What to remember
- Match the base case to the empty form of the data.
- Make recursive calls on the immediate child subtrees.
- Combine the current record's contribution with the returned child results.
- Include empty-child invocations when a question asks for every call.
A logging program converts a list of event names into text using the Python function below. It uses structural recursion, following the construction of a list from its first item and the remaining list. Match each role to the corresponding action for a nonempty input.
def encode(events):
if events == []:
return ""
first = events[0]
rest = events[1:]
remaining = encode(rest)
return first + ";" + remainingEvaluate encode(rest) to obtain text for the remaining names.
Read events[0] and events[1:] to expose the current name and the remaining list.
Form first + ";" + remaining to build the text for the current list.
Decomposition
Reconstruction
Recursive call
A fieldwork app counts labels containing at least five characters. Determine the number returned by the following call. Answer in qualifying labels, as an exact whole number.
def count_long(labels):
if labels == []:
return 0
contribution = 1 if len(labels[0]) >= 5 else 0
return contribution + count_long(labels[1:])
count_long(["lab", "field", "notes", "map", "sample", "data"])