Functions

Recursion

Recursive functions solve nested problems by calling themselves on smaller pieces.

A leaf node is the base case. It has no children, so the function can return its own value without making another recursive call.

Source

def total(node):
    subtotal = node["value"]
    for child in node["children"]:
        subtotal += total(child)
    return subtotal

print(total({"value": 2, "children": []}))

Output

2

A non-leaf node solves the same problem for each child, then combines those smaller totals with its own value.

Source

tree = {
    "value": 1,
    "children": [
        {"value": 2, "children": []},
        {"value": 3, "children": [{"value": 4, "children": []}]},
    ],
}

print(total(tree))

Output

10
factorial(3)factorial(2)factorial(1)factorial(0) ← base
Each call pushes a new frame with the same name and a smaller argument; the base case unwinds back up the stack.

Notes

See also

Run the complete example

Example code

Expected output

2
10

Execution time appears here after you run the example.