Library/Coding patterns that get asked/Graphs, trees and tables

Depth-first search and recursion on trees

95 min7 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Turn parent and child pairs into a dict of children and a dict of parents, find the top, and say why a walk down a tree needs no seen-set
  • Write recursion that returns an answer for a whole subtree, such as its size, height or total, and tell pre-order, in-order and post-order apart
  • Walk a tree deeper than Python's recursion limit with your own stack, and get post-order totals by reading the popping order backwards
  • Find the path from the top to a region and the smallest region that contains two others, each in time proportional to the depth
  • Count regions on a grid with depth-first search and a seen-set, choose it or breadth-first search for a reason, and backtrack with an undo step
  • Keep subtree totals right while values change, and answer the follow-ups: machines that only answer messages, a tree too big for memory, and writing a tree out and reading it back

Regions inside regions, the way the coding round asks

Smallest Common Region is on Airbnb's LeetCode tag lists (2 sources), an Airbnb candidate reported a tree whose every parent holds the sum of its children, with values that change (1 report), and two Netflix candidates describe their coding question as a depth-first search over a tree (2 reports). This lesson's practice problem is that shape, a travel site's regions, in three levels:

  1. RegionTree(lists) with top(), depth(region) and places_in(region): the tree from its lists, which come in any order.
  2. smallest_common(a, b): the smallest region that contains both.
  3. set_listings(region, count) and listings(region), where a read never walks the regions inside, on a chain of 50,000.
CallReturns
top(), with Japan's list first"Asia"
depth("Shibuya")4
places_in("Japan")8
smallest_common("Shinjuku", "Kyoto")"Japan"

The lesson builds it from trees up: recursion, a stack of your own, paths, depth-first search on graphs, and backtracking. 16 steps end with a small task in the editor.

Part 1 of 7about 8 min
Trees

A tree is a dict of children

A travel site files its listings under regions, and regions sit inside bigger regions. That's the example for this whole lesson.

Regions inside regions
Europe
Portugal
Lisbon District
Lisbon
Sintra
Cascais
Porto District
Porto
Spain
Andalusia
Seville
Granada
Catalonia

Each region sits directly inside exactly one other, except Europe, which sits inside none. Follow the regions upward from any one of them and you always end at Europe. That shape is a tree.

Predict

Portugal's subtree is Portugal with everything below it. How many regions does it hold?

Pick an answer above to see the rest

The input comes as pairs, so build one dict for each direction

Here is the tree the way input gives it: one row for each region.

# (region, the region directly containing it)
PAIRS = [
    ("Portugal", "Europe"), ("Spain", "Europe"),
    ("Lisbon District", "Portugal"), ("Porto District", "Portugal"),
    ("Lisbon", "Lisbon District"), ("Sintra", "Lisbon District"), ("Cascais", "Lisbon District"),
    ("Porto", "Porto District"),
    ("Andalusia", "Spain"), ("Catalonia", "Spain"),
    ("Seville", "Andalusia"), ("Granada", "Andalusia"),
]
print(len(PAIRS), "pairs")
12 pairs

The input rarely arrives drawn as a tree. It comes as rows, and each row names a region and its parent. Two dicts hold everything you'll need, one for each direction:

from collections import defaultdict


def build_tree(pairs):
    # region -> the regions directly inside it
    children = defaultdict(list)
    # region -> the region directly containing it
    parent = {}
    for region, outer in pairs:
        children[outer].append(region)
        parent[region] = outer
    tops = {outer for _, outer in pairs} - set(parent)
    return children, parent, tops


children, parent, tops = build_tree(PAIRS)
print(children["Lisbon District"])
print(parent["Sintra"])
print(tops)
print(len(children))
Predict

children is a defaultdict(list), filled from the 12 pairs. What does len(children) print?

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

A tree has one way down to each region, so a walk down needs no seen-set

Count the rows and the regions, and a rule appears.

Two ways round the rock on a grid
yard
Saab#abbE

From S to E through the a cells or the b cells. In a tree, Sintra has one way down: Europe, Portugal, Lisbon District, Sintra.

There are 13 regions and 12 pairs, one pair for each region except the top. That's always so: a tree with nn nodes has n−1n - 1 edges, the links between a parent and a child. So there's exactly one way down from the top to any region.

A walk that starts at the top and goes into every child reaches each region once, by that one way. It never comes back to a region. That's why tree code has no seen-set.

On the grid, E can be reached around either side of the rock, so the search had to remember what it had already queued. A tree has no second way round. A general graph does, and the seen-set comes back with it near the end of this lesson.

The practice problem writes the tree a second way, and this task uses it. There's one list for each region that holds others: the region first, then the regions directly inside it. So ["Portugal", "Lisbon District", "Porto District"] says Portugal directly holds those two districts. Porto holds nothing, so it gets no list of its own, and the lists come in any order.

In the editor, finish build_tree(lists). It builds a small tree whose top's list isn't first.

Part 1 done
Part 2 of 7about 20 min
Recursion

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

The calls go deep first, and each answer is built on the way back up

The order the calls run in gives depth-first search its name.

Predict

size("Portugal") calls size("Lisbon District") first. Which call is the first to return?

Pick an answer above to see the rest

Pre-order works before the children, post-order after them

Where the work sits next to the calls on the children decides what each region knows.

def walk(region, depth, pre, post):
    # pre-order: before the children
    pre.append((region, depth))
    for child in children[region]:
        walk(child, depth + 1, pre, post)
    # post-order: after them
    post.append(region)


pre, post = [], []
walk("Europe", 0, pre, post)
print(f"{'pre, with depth':<24}post")
for (region, depth), finished in zip(pre, post):
    print(f"{region + ' ' + str(depth):<24}{finished}")
Predict

post records a region after all its children. Which region comes first in post-order?

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

In-order means left, then the node, then right, and a search tree's keys come out sorted

Binary trees have a third order.

A binary search tree
147631314108

In-order only means something in a binary tree, where every node has at most a left child and a right child. It visits the left subtree, then the node, then the right subtree.

This one is a binary search tree: every key on a node's left is smaller than the node's key, and every key on its right is larger. So in-order gives the keys sorted. Sedgewick and Wayne's Algorithms textbook prints a search tree's keys in order this way.

Predict

Pre-order visits a node, then its left subtree, then its right. What's this tree's pre-order?

Pick an answer above to see the rest

One walk stores every subtree's answer

Often you want the size of every region, not one. Calling size once per region is correct and wasteful: the call for Portugal redoes the work already done for Lisbon District. On a chain, where each region holds exactly one region, the waste is a triangle:

Predict

A chain of 400 regions. Call size once for each region. How many calls in all?

Pick an answer above to see the rest
Part 2 done
Part 3 of 7about 18 min
Your own stack

Deeper than Python's recursion limit: keep your own stack

Every recursive walk above has a limit, and a deep tree finds it.

A chain, run from a scriptsize with sum(...)size with a for loop
frames per level2: the call and its generator1
frames at the deepest call1 + 2 × 499 = 9991 + 999 = 1,000
regions that fit499, and 500 don't999, and 1,000 don't

Each call that hasn't returned yet holds a frame on the call stack. Python's recursion limit caps how many frames can be in use at once. The docs call it the maximum depth of the Python interpreter stack. The default is 1,000, and going past it raises RecursionError.

A chain is the deep case: its height is n−1n - 1. Run from a script, size as written above raised RecursionError: maximum recursion depth exceeded at 500 regions. With a plain for loop in place of sum(...), it reached 999.

The generator expression inside sum runs in a frame of its own, and the script's top level, <module>, takes one more. In a notebook or a test runner, more frames are in use before your code starts, so the numbers can come out lower.

Raising the limit too far can crash Python, so keep the pending work in a list

sys.setrecursionlimit raises the limit. Python's docs warn that it should be done with care, because a limit set too high can crash Python.

Interview inputs come from someone else. A tree of a million nested comments, or a folder chain from a broken script, is fair game. The safe answer is to keep the pending work in a list you manage, instead of on Python's call stack.

A Python list is a stack already. append puts an item on the end, and pop() with no index takes the last one back off. Push the top, then pop a region, handle it, and push its children, until the stack is empty:

# pre-order work: known before the children
def depths_with_stack(children, top):
    depth = {top: 0}
    stack = [top]
    while stack:
        region = stack.pop()
        for child in children[region]:
            depth[child] = depth[region] + 1
            stack.append(child)
    return depth


depth = depths_with_stack(children, "Europe")
print(depth["Portugal"], depth["Sintra"], depth["Catalonia"])
1 3 2

Pre-order work fits straight in, because a child's depth is known the moment its parent is popped. Here is the stack after each pop on Portugal's subtree, with its top at the right end:

stack = ["Portugal"]
while stack:
    region = stack.pop()
    stack.extend(children[region])
    print(f"{region:<17}{stack}")
Predict

The stack starts as ["Portugal"]. Each pop puts the region's children on the end. Which region comes off second?

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

Your stack takes the children right to left, and recursion left to right

Both walks go as deep as they can, in a different order.

Visit order: recursion, then your stack
Portugal
1, 1
Lisbon District
2, 4
Lisbon
3, 7
Sintra
4, 6
Cascais
5, 5
Porto District
6, 2
Porto
7, 3

Both go as deep as they can before they back up. They differ in which child goes first. The last child pushed is the first popped, so your stack takes the children right to left.

Predict

Which one change makes your stack visit a tree in recursion's order?

Pick an answer above to see the rest

Read the popping order backwards, and every region comes after everything inside it

Post-order work, like sizes, needs every child finished first. A stack pops the parent before any child. The trick is to record the order in which regions come off the stack:

def sizes_with_stack(children, top):
    order, stack = [], [top]
    while stack:
        region = stack.pop()
        # each region lands after the one containing it
        order.append(region)
        stack.extend(children[region])
    sizes = {}
    # backwards: each region after everything inside it
    for region in reversed(order):
        total = 1
        for child in children[region]:
            total += sizes[child]
        sizes[region] = total
    return sizes


for region, n in sizes_with_stack(children, "Portugal").items():
    print(region, n)
Lisbon 1
Sintra 1
Cascais 1
Lisbon District 4
Porto 1
Porto District 2
Portugal 7

Every region is pushed by its parent, so it comes off after its parent. Read backwards, that order puts every region after everything inside it:

Order, as poppedSize, filled in from the bottom up
Portugal7 = 1 + 4 + 2, last
Porto District2 = 1 + 1
Porto1
Lisbon District4 = 1 + 1 + 1 + 1
Cascais1
Sintra1
Lisbon1, start here

By the time the backwards pass reaches a region, each of its children already has a size. The printed order, Lisbon to Portugal, is exactly the post-order the recursive walk gave. That holds on any tree: the popping order, read backwards, is post-order.

In the editor, write totals_with_stack(children, own, top). It totals three regions' listings up the Europe tree.

Recursion was faster when it fit, and only your stack got through a chain

Both are worth knowing, so measure them.

Tree, 100,000 regionsRecursive all_sizessizes_with_stack
Random, each region under an earlier one, height 2337.5 ms54.3 ms
A chain, height 99,999RecursionError17.1 ms

Medians of seven runs, Python 3.12, on the machine these numbers come from. When recursion fits, it's the faster of the two here, and the stack version spends a second pass on the stored order. When it doesn't fit, nothing else matters.

Both are O(n)O(n) time. The memory differs in kind, and the two shapes that pull it apart are the chain and the star, one top holding everyone else:

Predict

A star: one top over 99,999 regions. At its peak, how many regions sit on your stack?

Pick an answer above to see the rest
Part 3 done
Part 4 of 7about 9 min
Paths

Paths and the smallest common ancestor

With a parent dict, a question about a path is a climb.

def path_from_top(parent, region):
    path = [region]
    # the top has no parent, so the loop ends there
    while region in parent:
        region = parent[region]
        path.append(region)
    return path[::-1]


print(path_from_top(parent, "Sintra"))
['Europe', 'Portugal', 'Lisbon District', 'Sintra']

Going up needs no search at all. The walk is O(d)O(d), where dd is the region's depth. It's a loop, so a deep chain is no problem.

In the editor, write depth_of(parent, region) by climbing. It prints the depth of the top, of Sintra, and of the end of a chain of 50,000.

Collect everything that contains a, then climb from b until you reach one of them

Two climbs find the smallest region containing two others.

def smallest_common(parent, a, b):
    above_a = set(path_from_top(parent, a))
    while b not in above_a:
        b = parent[b]
    return b


for a, b in [("Sintra", "Porto"), ("Seville", "Lisbon"), ("Catalonia", "Seville"), ("Portugal", "Cascais")]:
    print(a, "and", b, "->", smallest_common(parent, a, b))
Predict

What's the smallest region that contains both Sintra and Porto?

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

Climb from Granada (depth 3) and Catalonia (depth 2) together, one step each, until they stand on the same region. Where do they meet?

Pick an answer above to see the rest

When a tree arrives as nested objects that only point down, there's no parent to climb. Find the path with a walk down that keeps the current path in a list. Append on the way in, and pop on the way out when the target wasn't below:

def path_down(children, top, target):
    path = []

    def visit(region):
        path.append(region)
        if region == target:
            return True
        for child in children[region]:
            if visit(child):
                return True
        # not under here: take it back off
        path.pop()
        return False

    visit(top)
    return path


print(path_down(children, "Europe", "Granada"))
['Europe', 'Spain', 'Andalusia', 'Granada']

The list grows on the way down and shrinks on the way back up:

Visitpath after it
EuropeEurope
PortugalEurope, Portugal
Portugal's subtreeits 7 regions go on, then come back off
back out of PortugalEurope
SpainEurope, Spain
AndalusiaEurope, Spain, Andalusia
SevilleEurope, Spain, Andalusia, Seville: not the target, so popped
GranadaEurope, Spain, Andalusia, Granada: the target, stop

This walk may visit the whole tree, O(n)O(n), against O(h)O(h) for the walk up. So build parent once if you'll ask more than one question. That path.pop() is your first undo step. Backtracking, later in this lesson, is built on it.

Part 4 done
Part 5 of 7about 20 min
Graphs and backtracking

Depth-first search on a graph

Leave trees for a general graph, like a grid, and two things change. A cell can be reached by more than one route, and routes can loop. So the seen-set comes back, for the same reason as in breadth-first search: without it, a walk goes round a loop forever.

On a graph the same walk is depth-first search, DFS for short. It reaches every cell connected to the start once, in O(RC)O(RC) time for RR rows and CC columns, the same as BFS.

SIDES = ((-1, 0), (1, 0), (0, -1), (0, 1))


def open_neighbors(grid, r, c):
    found = []
    for dr, dc in SIDES:
        nr, nc = r + dr, c + dc
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#":
            found.append((nr, nc))
    return found


print(open_neighbors(["..#...", "..#.##", "###...", ".#..#."], 0, 1))
[(1, 1), (0, 0)]

open_neighbors is the one from the grid BFS lesson. Counting the regions takes a scan and a search. Scan every cell, row by row, and skip walls and cells already in seen. Any other cell is one no earlier search reached, so it starts a new region: add 1 to the count, mark the cell, and push it on a stack. Then pop cells until the stack is empty, and push each open neighbor that isn't in seen yet, marking it as you push.

That's the grid BFS search with stack.pop() where it had queue.popleft().

Predict

The grid is ["..#...", "..#.##", "###...", ".#..#."], with # a wall. How many regions of open cells?

Pick an answer above to see the rest

On a grid, mark a cell when you pop it, and your stack visits in recursion's order

The order a stack visits a grid in can differ from recursion's.

Predict

Your stack marks a cell when it pushes it. From (0,0) on an open 3 by 4 grid, when does it visit (0,1), right next to the start?

Pick an answer above to see the rest

In a directed graph, a node you've seen is a second route or a cycle

Edges with a direction change what a node you've seen means.

Predict

DFS in a directed graph reaches a node it has already seen. What does that tell you?

Pick an answer above to see the rest

Pick DFS or BFS by what the question needs

Each search fits a different question.

Predict

Breadth-first from (0,0) on an open 3 by 4 grid, trying up, down, left, right. What number does (0,1), right of the start, get?

Pick an answer above to see the rest

Backtracking: undo on the way out

Some questions ask about paths, not cells. Word search is the classic, and it's on Netflix's LeetCode company tag list (1 source). Given a grid of letters, is there a path of side-by-side cells that spells a word, using each cell at most once?

Here the seen-set is wrong in the opposite way. A cell belongs to the current path, not to the search forever. So a cell a failed path used must be free for the next path. Mark a cell on the way in and unmark it on the way out. That unmarking is the undo step, and a DFS with an undo step is backtracking.

Here's the shape on a smaller question: how many routes go from the top-left corner of an open grid to the bottom-right, moving between side-by-side cells and never visiting a cell twice?

def routes(grid):
    goal = (len(grid) - 1, len(grid[0]) - 1)
    on_path = {(0, 0)}

    def extend(cell):
        if cell == goal:
            return 1
        found = 0
        for nxt in open_neighbors(grid, *cell):
            if nxt not in on_path:
                # step in
                on_path.add(nxt)
                found += extend(nxt)
                # undo: step back out
                on_path.remove(nxt)
        return found

    return extend((0, 0))


print(routes(["..", ".."]), routes(["...", "...", "..."]))
Predict

How many routes go from the top-left to the bottom-right of an open 2 by 2 grid, never visiting a cell twice?

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

Backtracking explores paths, and the number of paths can grow exponentially

The number of paths is what makes backtracking slow.

Predict

An open 3 by 3 grid has 12 routes from corner to corner. About how many does a 6 by 6 have?

Pick an answer above to see the rest

In word search, a word that almost fits is the slow case

For word search, a path can start at any of the RCRC cells. A word of L≥2L \ge 2 letters has at most 4⋅3L−24 \cdot 3^{L-2} paths from each start: 4 choices for the first step, then 3 for each step after, since one of the four neighbors is the cell you came from. That's O(RC⋅3L)O(RC \cdot 3^L).

A hard case is a 5 by 5 grid of As and a word of As with a B at the end. Every path of As stays alive, and the B is never there. Counting every call to match, the function this step's task asks for, tries outside the grid included:

Word lengthCalls to match
41,197
66,909
831,965
10122,685

The 10-letter word took 33.4 ms.

In the editor, write match(r, c, i) inside has_word(grid, word). It looks for three words on the classic grid.

Watch · 9 min

Word search drawn out, then coded from 3:06. Watch where the cell joins the current path before the four recursive calls and where it leaves the path after them. That's this section's step in and undo.

Word Search - Backtracking - Leetcode 79 - Python · NeetCode · Apr 2021YouTube
Part 5 done
Part 6 of 7about 5 min
The worked example

A worked example: folder sizes that stay right

An Airbnb software engineer candidate reported a tree whose leaves hold numbers and whose every other node holds the sum of its children, where values change and any node can be read in between (1 report). Here it is as disk usage.

The prompt: you get (item, folder) pairs and the size in bytes of each file. Support resize(file, size), and size_of(node): the bytes in a file, or in a folder and everything under it.

PAIRS = [("docs", "/"), ("photos", "/"), ("cv.pdf", "docs"), ("notes.txt", "docs"),
         ("beach.jpg", "photos"), ("2024", "photos"), ("trip.jpg", "2024")]
SIZES = {"cv.pdf": 120, "notes.txt": 4, "beach.jpg": 2300, "trip.jpg": 1800}
print(len(PAIRS), "pairs,", len(SIZES), "file sizes")
7 pairs, 4 file sizes

1. Clarify. Those answers pick the design:

  • Is resize given the new size or the change? The new size, here.
  • Can a folder hold bytes of its own? Say no, but make the code not care.
  • How many reads against changes, and how deep can it go? Reads far outnumber changes, and folders can nest thousands deep.

2. The obvious version. Store each file's size, and on every read walk the node's subtree with a stack and add up. A change is O(1)O(1). A read is O(s)O(s), where ss is the size of the subtree, so reading the top is O(n)O(n) every time. Here it is as a method of SizeTree, the class this worked example builds, which keeps each node's own bytes in self.own and its children in self.children:

def size_by_walking(self, node):
    total, stack = 0, [node]
    while stack:
        item = stack.pop()
        total += self.own[item]
        stack.extend(self.children[item])
    return total

A change moves only the totals on its path to the top

3. The insight. A change to one file moves exactly the totals of the folders that contain it: its ancestors, the path from it to the top. Nothing else. So store every node's total once, with one post-order pass. On a change, walk up parent adding the difference. A read becomes a lookup.

from collections import defaultdict


class SizeTree:
    def __init__(self, pairs, file_sizes):
        self.parent, self.children = {}, defaultdict(list)
        for item, folder in pairs:
            self.parent[item] = folder
            self.children[folder].append(item)
        top = next(folder for _, folder in pairs if folder not in self.parent)
        # bytes stored at the node itself
        self.own = defaultdict(int, file_sizes)
        order, stack = [], [top]
        while stack:
            node = stack.pop()
            order.append(node)
            stack.extend(self.children[node])
        self.total = {}
        # backwards: post-order, as with sizes_with_stack
        for node in reversed(order):
            self.total[node] = self.own[node] + sum(self.total[c] for c in self.children[node])

    def size_of(self, node):
        return self.total[node]

    def resize(self, file, size):
        change = size - self.own[file]
        self.own[file] = size
        node = file
        # the file, then each folder above it
        while node is not None:
            self.total[node] += change
            node = self.parent.get(node)


tree = SizeTree(PAIRS, SIZES)
print([tree.size_of(node) for node in ["/", "docs", "photos", "2024"]])
tree.resize("trip.jpg", 1500)
print([tree.size_of(node) for node in ["/", "docs", "photos", "2024"]])
Predict

photos holds beach.jpg (2300 bytes) and the folder 2024, which holds trip.jpg (1800). What's size_of("photos") before the resize?

Pick one to see what it prints.
Predict

resize("trip.jpg", 1500) on a file of 1800 bytes. What does the walk add to each total on its way up?

Pick an answer above to see the rest

Test the edges, then measure both costs

5. Edge cases.

  • The walk up ends when parent.get returns None after the top. So a file sitting directly in / works like any other.
  • A file nested 100,000 folders deep works too, since every walk is a loop.
  • A new file that wasn't in the pairs is a clarifying question. Add it to parent and children with its folder, give it a total of 0, then resize it.

6. Cost, measured. On a random tree of 100,000 nodes, each under a random earlier one, with sizes on its 50,089 leaves, medians of five runs:

Read the topChange one file
Walk the subtree on every read32.57 msO(1)O(1)
Keep totals, walk up on every change44 ns1.78 µs, 12.3 nodes walked on average
Keep totals, on a chain of 100,00043 ns5.76 ms at the bottom

Building took 124.0 ms, once. Keeping totals turns every read into a lookup and every change into O(h)O(h). On a chain, hh is nn, and the change at the bottom costs nearly what a full read costs the other way: walking the chain's 100,000 nodes took 8.38 ms. Say that trade out loud. Then offer the fix for when both are frequent on a deep tree: number the nodes in pre-order, so every subtree is one range of numbers.

Part 6 done
Part 7 of 7about 15 min
Follow-ups

When changes and reads are both frequent on a deep tree, number the nodes in pre-order

Walking up is O(h)O(h) per change, and walking down is O(s)O(s) per read. Number the nodes in pre-order, and every subtree is one unbroken range of numbers.

Predict

Number the regions in pre-order from 0. Europe is 0 and Portugal is 1. Which numbers make up Portugal's subtree?

Pick an answer above to see the rest

When a parent's choice depends on its child's, return two numbers from each subtree

A prep site lists the largest sum of tree values with no two chosen nodes next to each other for an Airbnb senior loop (1 source). Next to each other means parent and child.

One number per subtree isn't enough, because the parent's choice depends on whether the child was taken. So each node returns two:

  • take: the best total if it's taken. Then its children must be skipped.
  • skip: the best total if it's skipped. Then each child is free to be either.
VALUE = {"Europe": 5, "Portugal": 4, "Spain": 6, "Lisbon District": 3, "Porto District": 2,
         "Lisbon": 8, "Sintra": 1, "Cascais": 2, "Porto": 7, "Andalusia": 9, "Catalonia": 3,
         "Seville": 4, "Granada": 4}
print(best_without_neighbors(children, VALUE, "Europe"))
36
Predict

Lisbon District has value 3, and its leaves Lisbon, Sintra and Cascais have 8, 1 and 2. What's the best total there, never taking a parent and its child?

Pick an answer above to see the rest

When the nodes are machines that only answer messages, count in post-order over the network

Two OpenAI candidates report a question about counting the machines in a tree when all you have is a call that sends a message to a machine (2 reports). It's post-order sizes, spread over a network:

Predict

Each machine forwards a count request to its children and answers its parent once. How many messages for n machines?

Pick an answer above to see the rest

When the tree is too big for memory, start at the leaves and release a parent when its last child reports

Keep the tree as (child, parent) rows in a database or in files. Totals still come from the bottom up, and a release-when-ready loop gets them without knowing any depths:

  1. Count each node's children.
  2. Start from the leaves.
  3. When a node's last child has reported, add the node's total into its parent's, and release the parent.

The topological sort lesson builds the same loop. With the counts and totals in a key-value store, only the nodes ready to report sit in memory. A database can do the same walk in one recursive query (WITH RECURSIVE). For a deep but not huge tree, your own stack is the whole fix.

To write a tree out and read it back, store each node's number of children in pre-order

A tree can be saved as one flat list and rebuilt from it.

Predict

A chain, A over B over C, and a fork, A over both B and C. Do their pre-orders differ?

Pick an answer above to see the rest
Predict

You write a chain 100,000 deep as nested JSON lists with json.dumps, then read it back with json.loads. What happens?

Pick an answer above to see the rest

Is it really a tree? Check one parent each, one top, and that the top reaches every node

Input from someone else may not be a tree at all.

Predict

Every node has at most one parent, and exactly one node has none. Can it still fail to be a tree?

Pick an answer above to see the rest

The tests you'd write cover one node, a long chain, a star and the awkward inputs

  • One node.
  • A chain longer than 1,000, listed top first and listed bottom first.
  • A star, one node over thousands.
  • The top's row not first.
  • Leaves with no row of their own.
  • The smallest common ancestor of a node and itself, of a node and its own descendant, and of two nodes at different depths.
  • A value set twice.
  • A change at the top.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the three levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
6 questions
  1. 1.Why does a walk down a tree from its top not need a seen-set, when a walk over a grid does?

  2. 2.A recursive size written as 1 + sum(size(child) for child in children[node]) handles a chain of 499 nodes and raises RecursionError at 500. Written with a plain for loop, it reaches 999. Why the difference?

  3. 3.Which of these can only be computed after a node's children are done?

  4. 4.With your own stack, you record the order regions come off it, then compute subtree sizes walking that order. Which direction works?

  5. 5.Word search marks each cell it steps on. What breaks if it never unmarks a cell when it backs out?

  6. 6.You keep a total per node and walk up the parents on every change. On a chain of 100,000 nodes, what does a change at the bottom and a read of the top cost?

Practice

Sources (6)
  1. sys.getrecursionlimit · Python 3.12 documentation · Oct 26, 2026
    “Return the current value of the recursion limit, the maximum depth of the Python interpreter stack.”
  2. sys.setrecursionlimit · Python 3.12 documentation · Oct 26, 2026
    “This should be done with care, because a too-high limit can lead to a crash.”
  3. Built-in Exceptions: RecursionError · Python 3.12 documentation · Oct 26, 2026
    “It is raised when the interpreter detects that the maximum recursion depth (see sys.getrecursionlimit()) is exceeded.”
  4. Data Structures: Using Lists as Stacks · Python 3.12 documentation · Oct 26, 2026
    “To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.”
  5. 4.1 Undirected Graphs · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Apr 16, 2019
    “DFS marks all the vertices connected to a given source in time proportional to the sum of their degrees and provides clients with a path from a given source to any marked vertex in time proportional to its length.”
  6. 3.2 Binary Search Trees · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Mar 19, 2021
    “print all the keys in the left subtree (which are less than the key at the root by definition of BSTs), then print the key at the root, then print all the keys in the right subtree”