Functions
Recursion
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
2A 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
10Notes
- Every recursive function needs a base case that stops the calls.
- Recursion fits nested data better than flat repetition.
- Python limits recursion depth, so loops are often better for very deep or simple repetition.
See also
- related: Functions
- prerequisite: Conditionals
- next depth: Generators
Run the complete example
Expected output
2
10
Execution time appears here after you run the example.