Recursion: base case and walking trees

Advanced Python for Data Science
Created by Best · 24.06.2026 at 14:03 UTC

A lot of data is a tree: nested JSON, a folder hierarchy, a category taxonomy. Recursion is a function that calls itself on a smaller piece of the problem until the piece is trivial. Every recursion needs a base case (when to stop) and a recursive case (reduce the problem and call itself).

Summing every value in a tree reads almost like its own definition — a node's total is its own value plus the totals of its children:

def tree_sum(node):                      # node = {"val": int, "children": [...]}
    return node["val"] + sum(tree_sum(c) for c in node["children"])

Here the base case is a node with no children (the sum of an empty list is 0).

The recursive shape generalises to any nested structure. Reading arbitrarily nested JSON, computing a maximum depth, or totalling values are all the same pattern: handle the current node, then recurse into its children.

import json
root = json.loads(text)        # a nested dict/list tree
print(tree_sum(root))

Code that mirrors a tree's shape is short and obviously correct, which is why recursion is the natural language of hierarchical data. The same idea also drives binary-tree traversals — and an in-order walk of a binary search tree visits values in sorted order.
and leads into “Explicit stacks and the recursion limit”.*

University approvals: 0
Related cards
Builds on Chunked reading and single-pass generators · Python for Data Science
Next Explicit stacks and the recursion limit · Python for Data Science
Tasks
Question 1

What must every recursive function have to avoid running forever?

Question 2

stdin is one line of JSON: a tree node {"val": int, "children": [...]} nested arbitrarily. Print the sum of all val fields in the tree.

Example input:

{"val": 1, "children": [{"val": 2, "children": []}, {"val": 3, "children": [{"val": 4, "children": []}]}]}

Expected output:

10
3 test cases will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Python for Data Science
  • Difficulty: Advanced
  • Completed: 0 users
Creator
Best
Best
BestBuddy