5/38
Part 2 of 7 · RecursionLearn and do

Recursion returns an answer for a whole subtree

A tree question usually asks about a whole subtree, and recursion answers it.

# regions in the subtree, itself included
def size(region):
    return 1 + sum(size(child) for child in children[region])


# steps on the longest way down to a leaf
def height(region):
    return 1 + max((height(child) for child in children[region]), default=-1)


print(size("Europe"), size("Portugal"), size("Seville"))
print(height("Europe"), height("Spain"), height("Porto"))
Predict

height counts the steps on the longest way down to a leaf. What's height(Europe)?

Pick one to see what it prints.
Pick an answer above to see the rest