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 stock tree has root value 6, child values 4 and 3, a right child value 2 below 4, and a left child value 1 below 3.


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.


Python
def total_boxes(node):
    if node is None:
        return EMPTY_TOTAL
    return node.boxes + LEFT_TOTAL + RIGHT_TOTAL


A 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:


T(empty)=0,T(node)=node.boxes+T(left)+T(right).T(\text{empty})=0, \qquad T(\text{node})=\text{node.boxes}+T(\text{left})+T(\text{right}).


The completed function is


Python
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=22+0+0=2 boxes, and the section storing 1 box returns 1+0+0=11+0+0=1 box.


The subtree rooted at the 4-box section returns ________, because


Tleft=4+0+2=6 boxes.T_{\text{left}}=4+0+2=6\ \text{boxes}.


The subtree rooted at the 3-box section returns ________, because


Tright=3+1+0=4 boxes.T_{\text{right}}=3+1+0=4\ \text{boxes}.


Finally, the root combines its own stock with both returned totals:


Troot=6+6+4=16 boxes.T_{\text{root}}=6+6+4=16\ \text{boxes}.


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


1+1+2+2=6 calls.1+1+2+2=6\ \text{calls}.


Adding the two kinds of invocation gives


5+6=11 calls.5+6=11\ \text{calls}.


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 game records signed point adjustments in a Python list. Which replacement for BASE makes this structurally recursive function return their total, including when the list is empty?


Python
def total_points(adjustments):
    if adjustments == []:
        return BASE
    return adjustments[0] + total_points(adjustments[1:])
Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.


Python
def encode(events):
    if events == []:
        return ""
    first = events[0]
    rest = events[1:]
    remaining = encode(rest)
    return first + ";" + remaining
Match each term
A.

Evaluate encode(rest) to obtain text for the remaining names.

B.

Read events[0] and events[1:] to expose the current name and the remaining list.

C.

Form first + ";" + remaining to build the text for the current list.

Decomposition

Reconstruction

Recursive call

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

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.


Python
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"])

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice