Trees are where you can’t avoid recursion any more. A tree is a node plus two smaller trees hanging off it. So almost every tree algorithm comes down to two questions: what does a node hand down to its children, and what does it expect back?

This topic builds on two earlier ones. Binary Search matters because a BST is binary search stored as nodes. Linked List matters because a tree node is just a list node with two next pointers. After this come Tries, Heap / Priority Queue and Backtracking, which all reuse the traversals taught here. The post ends with the fifteen tree problems from the problem set.

How to use this post: the method. The checkpoints don’t show answers on the page. Work each one out yourself first, then open the linked chat to have your answer checked.

All code in this post uses one node class:

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

BST Insert and Remove

Foundation

Think of a binary search tree (BST) as a sorted array folded into nodes. A node’s subtree is that node plus everything below it. Every node in a BST obeys one rule: all keys in its left subtree are smaller than it, and all keys in its right subtree are larger.

This rule does the same job that sortedness does in binary search. One comparison at a node rules out a whole subtree. So a lookup follows a single path from the root down to a leaf (a node with no children), instead of scanning everything.

Why not just keep a sorted array? Because a BST is cheap to change. Inserting into a sorted array means shifting O(n) elements over. Inserting into a BST just attaches a new leaf at the end of that one path.

Mechanics

Our worked tree: start with an empty BST and insert 8, 3, 10, 1, 6, 14, 4, 7, 13 in that order.

Insert walks down exactly the way a search would. At each node you compare. Smaller goes left, larger goes right. The first empty slot you reach is where the key belongs.

Let’s insert 7. It goes left at 8 (7 < 8), right at 3 (7 > 3), and right at 6 (7 > 6). The right slot under 6 is empty, so 7 lands there.

Why is it safe to ignore the other side each time? Take node 3. Everything in 3’s left subtree is below 3. But 7 is above 3, so 7 can never belong there.

Remove has three cases. Which one you’re in depends on how many children the target node has:

  1. Leaf (0 children). Cut it off. Nothing below it needs a new parent.
  2. One child. Hand that child up to the removed node’s parent. Is the child’s subtree still on the correct side of every ancestor? Yes. It sat under the removed node, and the removed node was on the correct side, so everything under it was too.
  3. Two children. You can’t just splice the node out, because two subtrees would be fighting over one slot. Instead, copy in the in-order successor: the smallest key in the right subtree. Then delete the successor from the right subtree.

Let’s check case 3 on the worked tree by removing 3. Its right subtree holds {6, 4, 7}, and the smallest of those is 4. Put 4 where 3 was. Does the BST rule still hold?

  • 4 is greater than everything in the left subtree ({1}). That’s because 4 came from 3’s right side, so 4 > 3 > 1.
  • 4 is smaller than everything still in the right subtree ({6, 7}). That’s because it was that subtree’s minimum.

So the BST rule still holds at the new node. The last step is deleting the successor (here, 4) from the right subtree. That’s always case 1 or 2, never case 3. Why? The minimum can’t have a left child. If it did, that child would be even smaller, and the minimum wouldn’t be the minimum.

Diagram

The worked BST before remove(3)8 at the root; 3 left with children 1 and 6; 6 has children 4 and 7; 10 right with right child 14; 14 has left child 13. 3 is the node to remove, 4 its in-order successor.831016144713LRLRLRRLbefore remove(3)removein-order successor
The worked BST after remove(3)4 now sits where 3 was, with left child 1 and right child 6; 6 keeps only its right child 7; the right side 10, 14, 13 is unchanged.841016147134LRLRRRLafter remove(3)4 copied upold leaf 4 deleted

Two more removals follow. remove(14) is case 2 (one child), so 13 moves up to become 10’s right child. remove(7) is case 1 (a leaf), so 7 is simply cut off.

Implementation

def insert(root, val):
    """Insert val into the BST rooted at root; return the (possibly new) subtree root."""
    if root is None:
        return TreeNode(val)                  # the empty slot where val belongs
    if val < root.val:
        root.left = insert(root.left, val)    # every key in root.right is > root.val > val
    elif val > root.val:
        root.right = insert(root.right, val)  # every key in root.left is < root.val < val
    # val == root.val: already present; a set ignores duplicates
    return root


def remove(root, val):
    """Remove val from the BST rooted at root; return the new root of this subtree."""
    if root is None:
        return None                           # val was never in the tree
    if val < root.val:
        root.left = remove(root.left, val)
    elif val > root.val:
        root.right = remove(root.right, val)
    else:
        # 0 children: root.left is None, so root.right (also None) replaces root
        # 1 child: whichever side is not None replaces root
        if root.left is None:
            return root.right
        if root.right is None:
            return root.left
        # 2 children: succ = smallest key in root.right; it is > every key in root.left
        # and < every other key in root.right, so it can sit where root.val was
        succ = root.right
        while succ.left:
            succ = succ.left
        root.val = succ.val
        # succ has no left child, so this nested call ends in the 0- or 1-child branch
        root.right = remove(root.right, succ.val)
    return root


def inorder(root):
    return inorder(root.left) + [root.val] + inorder(root.right) if root else []


root = None
for v in [8, 3, 10, 1, 6, 14, 4, 7, 13]:
    root = insert(root, v)
print(inorder(root))          # [1, 3, 4, 6, 7, 8, 10, 13, 14]
for v in [3, 14, 7]:
    root = remove(root, v)
    print(v, inorder(root))
# 3 [1, 4, 6, 7, 8, 10, 13, 14]
# 14 [1, 4, 6, 7, 8, 10, 13]
# 7 [1, 4, 6, 8, 10, 13]

Both functions return the root of the subtree they worked on. That lets the caller write root.left = remove(root.left, val). If the subtree’s root changed or disappeared, this line re-attaches whatever replaced it. The same trick works for the whole tree’s root.

Edge cases I ran: removing from an empty tree returns None, and so does removing the only node. Removing a key that isn’t there leaves the tree unchanged.

Complexity: both operations follow one root-to-leaf path. The height h of a tree is the number of nodes on its longest root-to-leaf path. So time is O(h), and the recursion stack also takes O(h) space.

For n keys, h is about log2(n) when the tree is balanced (both sides roughly the same size), and n in the worst case. The worked tree has 9 keys and height 4. But if you insert 1 through 100 in order, every key goes right and you get height 100. That’s a linked list with extra steps.

Recognition

Signals that you need this:

  • The input is described as a binary search tree.
  • You need a collection that stays sorted while keys are added and removed.

When NOT to hand-roll one:

  • If you only need exact lookups, a hash set is O(1) on average.
  • If the keys never change, a sorted array plus binary search is simpler.

In interviews you write the plain BST, and you mention that production code would use a balanced one.

No problem in this topic’s list asks you to insert or delete. But three of them depend on the ordering rule this module rests on: Validate Binary Search Tree, Kth Smallest Element In a Bst, and Lowest Common Ancestor of a Binary Search Tree.

Pitfalls

  • Forgetting to re-assign the return value. If you write remove(root.left, val) without root.left =, the deletion happens in a subtree that never gets re-attached.
  • Deleting the successor from the wrong place in case 3. Delete it from root.right, not from the whole tree. Otherwise you can end up deleting the wrong node or walking the wrong path.
  • Assuming O(log n). A plain BST is only as good as the order the keys were inserted in.
  • Duplicates. Decide up front what to do with them: ignore them (a set), overwrite the value (a map), or keep a count. If insert uses <= and search uses < (or the other way round), you lose keys.

Active Recall

  1. Insert 5 into the original worked tree (before any removals). Name the path and where 5 ends up.

  2. Remove 8 (the root) from the original tree. What is the new root, and what does the right subtree look like?

  3. You remove 3 using the predecessor instead of the successor. What replaces 3, and is the tree still valid?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Judgment call: this one stays. No problem in this list inserts into or deletes from a BST, so you won’t practise these mechanics anywhere else.

You’re given the root of a BST and two numbers lo and hi. Return the tree with every key outside [lo, hi] removed. Every surviving node must keep its correct BST position relative to the others. On the worked tree with lo = 4, hi = 10, the surviving keys are 4, 6, 7, 8, 10.

Before any code, write down four things: the observation, the approach, why it’s correct, and the complexity.

Work it out, then talk it through withChatGPT ↗Claude ↗

Transfer test

You’re logging events keyed by timestamp. Timestamps arrive in strictly increasing order, and you need insert, delete-by-key and “next event after time t”. A colleague suggests a plain BST. Would you use it? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Foundation

Depth-first search (DFS) visits a tree by going as deep as it can down one branch, then backing up to try the next one. Recursion gives you this for free. A call on a node makes a call on its left child, and that call runs all the way to completion before the call on the right child even starts.

The picture that carries most tree problems is a node as a manager. The manager asks each of its two children, “give me the answer for your subtree.” It waits for both answers, then combines them with its own value. The empty tree (None) is the base case: every chain of asking eventually reaches it.

Information can flow two ways:

  • Top-down: the parent passes something down as an argument, like a running total, the current depth, or a bound.
  • Bottom-up: the child returns something up, like a subtree size, a sum, or a flag.

Many problems use both. The function returns one thing to its parent, and on the side it also updates a separate “best so far” answer.

Mechanics

The worked binary tree1 at the root; left child -2 with children 4 and -5; right child 3 with only a right child 6, its left child is None.1-234-56RNoneplain binary tree, not a BST

Three visiting orders. At each node you do some work, like recording its value. The order you get depends on when you do that work compared with the two recursive calls:

Order Work happens Worked tree
Preorder before both children 1, -2, 4, -5, 3, 6
Inorder between left and right 4, -2, -5, 1, 3, 6
Postorder after both children 4, -5, -2, 6, 3, 1

Preorder sees a node before anything under it. That makes it the natural place to pass information down. Postorder sees a node after everything under it. That makes it the only place where a node can use its children’s results. On a BST, inorder gives you the keys in sorted order (you saw that in the previous module).

Bottom-up example: largest subtree sum. Each node’s subtree sum is node.val + left_sum + right_sum, and an empty subtree has sum 0. This only works in postorder, because both child sums have to exist before you can add them.

There’s a catch. The value you return (this subtree’s sum) is not the value you want (the largest sum anywhere in the tree). So we keep the largest one in a variable outside the recursion. Here it is computed in postorder:

Node left sum right sum subtree sum best so far
4 0 0 4 4
-5 0 0 -5 4
-2 4 -5 -3 4
6 0 0 6 6
3 0 6 9 9
1 -3 9 7 9

The answer is 9, from the subtree rooted at 3. The root’s own sum is only 7. If you returned the root’s value as the answer, you’d get it wrong. That’s why the return value and the answer have to be kept apart.

Top-down example: every root-to-leaf sum. Pass the running total down as an argument. When you reach a node with no children, that total is a finished path. The three paths are 1 + (-2) + 4 = 3, 1 + (-2) + (-5) = -6, and 1 + 3 + 6 = 10.

Diagram

Call tree for the subtree-sum DFSEach box is one dfs call and what it returns. dfs(3) returns 9 and sets best to 9, which is the final answer; the root returns 7.dfs(1)1 + (-3) + 9 = 7dfs(-2)-2 + 4 + (-5) = -3dfs(3)3 + 0 + 6 = 9best = 9dfs(4)returns 4dfs(-5)returns -5dfs(None)returns 0dfs(6)returns 6answersubtree-sum DFS: each box is one call and what it returns

Implementation

def sample():
    return TreeNode(1,
                    TreeNode(-2, TreeNode(4), TreeNode(-5)),
                    TreeNode(3, None, TreeNode(6)))


def preorder(node, out):
    if node is None:
        return
    out.append(node.val)      # work before children
    preorder(node.left, out)
    preorder(node.right, out)
# inorder / postorder: move the append between / after the two calls


def max_subtree_sum(root):
    best = float("-inf")      # -inf, not 0: with all-negative values the answer is negative

    def dfs(node):
        nonlocal best
        if node is None:
            return 0          # empty subtree adds nothing to its parent's sum
        left = dfs(node.left)             # postorder: both child sums exist
        right = dfs(node.right)           # before node's own sum is formed
        total = node.val + left + right   # at node -2: -2 + 4 + (-5) = -3
        best = max(best, total)           # the answer lives here...
        return total                      # ...the parent only needs this

    dfs(root)
    return best


def root_to_leaf_sums(root):
    sums = []

    def dfs(node, running):
        if node is None:
            return
        running += node.val               # top-down: the parent's total arrives as an argument
        if node.left is None and node.right is None:
            sums.append(running)          # a path ends only at a real leaf
            return
        dfs(node.left, running)
        dfs(node.right, running)

    dfs(root, 0)
    return sums


out = []
preorder(sample(), out)
print(out)                            # [1, -2, 4, -5, 3, 6]
print(max_subtree_sum(sample()))      # 9
print(root_to_leaf_sums(sample()))    # [3, -6, 10]

Edge cases I ran:

  • root_to_leaf_sums(None) returns [].
  • max_subtree_sum on a single node -7 returns -7.
  • On the tree -1 (children -2, -3) it returns -2.
  • On an empty tree it returns -inf. Decide what an empty input should mean before you let that value out.

Complexity: every node is visited once, so time is O(n) for n nodes. Space is O(h) for the call stack, where h is the height. That’s O(log n) for a balanced tree and O(n) for a chain. root_to_leaf_sums also stores one number per leaf.

Recognition

Signals that DFS fits:

  • A node’s answer depends on its subtrees’ answers. Look for words like “height”, “size”, “sum”, “is it balanced” or “same shape”.
  • Something builds up along a path from the root. Look for “path”, “ancestor” or “depth so far”.
  • You need to visit every node, and the order doesn’t matter much.

In this list, Invert Binary Tree, Maximum Depth, Diameter, Balanced Binary Tree, Same Tree, Subtree of Another Tree, Count Good Nodes, and Binary Tree Maximum Path Sum all show these signals. Several of them also have the “return one thing, track another” shape from the subtree-sum example.

When NOT to reach for it first: when the question is about levels or rows, or about the nearest or shallowest match. That’s BFS, the next module. DFS can answer those questions too, but it has to explore deep branches that BFS would never need to touch.

How does this differ from the backtracking you’ll meet in Part 11? Backtracking is DFS over a tree of choices that you build as you go. Here the tree already exists.

Pitfalls

  • Missing the None base case, or reading node.left.val without first checking that node.left exists.
  • Detecting leaves at None instead of at the node. Suppose root_to_leaf_sums appended its total whenever it reached None. A real leaf has two None children, so its total would be recorded twice. Node 3 has a None left child, so you’d also get a made-up “path” ending at 3. On the worked tree that returns [3, 3, -6, -6, 4, 10, 10] instead of [3, -6, 10].
  • Starting the global best at 0 when values can be negative.
  • Using a mutable default argument, like def f(node, out=[]). That one list is shared across every call. This is recalled Python behaviour, and it bites when you run tests repeatedly.
  • Returning the global answer from the recursion instead of the value the parent needs.

Active Recall

  1. In the subtree-sum function, why must total be computed after both recursive calls and not before?

  2. Change best = float("-inf") to best = 0 and run it on the tree -1 with children -2 and -3. What comes back, and what should?

  3. Two different trees both have preorder [1, 2]. Draw them. Does inorder tell them apart?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Judgment call: skipped. Maximum Depth, Diameter, Balanced Binary Tree and Binary Tree Maximum Path Sum each make you build a combine-the-children DFS from scratch. So you’ll get that practice when you solve them.

Transfer test

An org chart: each manager has a list of direct reports (any number, not two). For every manager you need the total headcount beneath them, counting reports of reports. Would you use DFS? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Foundation

Picture a building being evacuated floor by floor. Nobody from floor 3 leaves until everyone on floor 2 is out. Breadth-first search (BFS) visits a tree the same way, level by level. First the root, then everything one edge down, then everything two edges down.

The tool for this is a queue: first in, first out, like a line at a shop. The current level is served from the front. Their children join the back. So a deeper level can’t be served until the shallower one in front of it is finished.

Mechanics

The worked tree by levelLevel 0 holds 1; level 1 holds -2 and 3; level 2 holds 4, -5 and 6.1-234-56Rlevel 0level 1level 2

Plain BFS order on the worked tree is 1, -2, 3, 4, -5, 6. But often you also need to know where one level ends. The trick is to record the queue’s length at the start of each round. At that moment, the queue holds exactly one full level and nothing else.

Why is that always true? It’s an invariant: a fact that stays true every time the loop comes back around. Here’s the argument:

  • At the start, the queue holds only the root. That’s all of level 0.
  • During a round, you pop exactly size nodes, which is all of level k. You push only their children, which is all of level k + 1, left to right.
  • So when the round ends, level k is gone and level k + 1 is complete. The fact holds again.

Worked example: sum each level. The level sums are 1, then -2 + 3 = 1, then 4 + (-5) + 6 = 5. That gives [1, 1, 5].

Diagram

BFS queue at the start of each roundRound 0: [1], size 1, sum 1. Round 1: [-2, 3], size 2, sum 1. Round 2: [4, -5, 6], size 3, sum 5. Round 3: empty, loop ends.roundqueue at round start, front leftsizelevel sum01111-232124-56353empty: loop ends

Implementation

from collections import deque


def level_sums(root):
    if root is None:
        return []
    sums = []
    queue = deque([root])     # deque: popleft is O(1) (recalled); list.pop(0) is O(n)
    while queue:
        size = len(queue)     # exactly one level is queued right now
        total = 0
        # range(size) is fixed here: the children appended below wait for the next round
        for _ in range(size):
            node = queue.popleft()
            total += node.val
            if node.left:
                queue.append(node.left)     # left before right keeps each level left-to-right
            if node.right:
                queue.append(node.right)
        sums.append(total)
    return sums


print(level_sums(sample()))   # [1, 1, 5]

I ran it with the queue printed at the start of each round. It showed [1], then [-2, 3], then [4, -5, 6], matching the diagram. Edge cases:

  • An empty tree gives [].
  • A single node 5 gives [5].
  • A left-leaning chain 1, 2, 3 gives [1, 2, 3], one node per level.

Complexity: each node goes into the queue once and comes out once, so time is O(n). Space is O(w), where w is the tree’s maximum width (the most nodes on any one level). In a complete tree the last level holds about n/2 nodes, so that’s O(n). For a chain it’s O(1).

Recognition

Signals that BFS fits: words like “level”, “row”, “depth-by-depth”, “from left to right on each level”, “the first/nearest/shallowest node that…”, or “minimum number of steps”. In this list, Binary Tree Level Order Traversal and Binary Tree Right Side View show the level signal directly.

When NOT to use it: when a node’s answer comes from its children’s answers (sizes, sums, heights). Bottom-up DFS is shorter there, and it uses O(h) memory rather than O(w).

So on a tree, DFS vs BFS is mostly about which order the problem cares about. Both visit every node in O(n).

Pitfalls

  • Letting one level bleed into the next. for _ in range(len(queue)) is safe, because range reads len(queue) once, at the start (recalled Python semantics, verified here). An inner while queue: is not safe. It keeps eating the children you just appended. On the worked tree it returns a single “level”, [1, -2, 3, 4, -5, 6].
  • Using list.pop(0). It shifts every remaining element over by one, which turns BFS into O(n²) on wide trees.
  • Putting None children in the queue and then reading from them. Either check before appending (as the code above does) or skip None right after popping. Pick one and do it consistently.
  • Forgetting the empty-root check before putting the root in the queue.

Active Recall

  1. Right after round 1 finishes, what is in the queue, and why is -5 guaranteed to sit before 6?

  2. Swap the deque for a stack: pop() from the back instead of popleft(). Keep the same push order (left, then right). What order do you get on the worked tree?

  3. For a perfect binary tree with 1,023 nodes (10 levels), roughly how much memory do BFS and recursive DFS need at their peak?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Judgment call: skipped. Binary Tree Level Order Traversal and Binary Tree Right Side View both make you build level-by-level BFS yourself. That’s where you’ll practise it.

Transfer test

A company tree (CEO at the root). You need the smallest number of management steps from the CEO to any employee whose title is “Security Lead”. The tree is very deep in some departments. Would you use BFS? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

BST Sets and Maps

Foundation

Many languages use a BST to build an ordered set (keys only) or an ordered map (each key points to a value). Java’s TreeMap and C++’s std::map are balanced BSTs (recalled).

Compare that with a hash map. A hash map answers “is this key here?” in O(1) on average, but it knows nothing about order. A balanced ordered map answers the same question in O(log n). In exchange, it can also answer order questions a hash map can’t:

  • What’s the smallest key? The largest?
  • What’s the next key above x? The previous key below x?
  • What are all the keys, in sorted order?

Python’s standard library has no tree-based map (recalled). dict is a hash map. It remembers the order you inserted keys in, not their sorted order. When you need sorted order in Python, you have three options: a sorted list with bisect, the third-party sortedcontainers package (recalled), or a BST you write yourself.

Mechanics

We’ll reuse the worked BST from module 1: 8, 3, 10, 1, 6, 14, 4, 7, 13, before any removals. Each map node now carries a key and a val. Search compares keys exactly the way insert did.

get(key) walks one path down. put(key, val) walks the same path. If the key already exists, it overwrites the value. If not, it attaches a new leaf.

floor(x) is the largest key ≤ x. This is where the BST ordering does real work. You keep a best candidate and walk down from the root:

  • At a node with key > x, this key is too big. So is everything in its right subtree, since those are even bigger. Go left.
  • At a node with key ≤ x, this key is a valid candidate, so record it. Could there be a better one? It would have to be larger but still ≤ x. The only larger keys below here are in the right subtree. Go right.

Trace for floor(5):

  • At 8: 8 > 5, so go left.
  • At 3: 3 ≤ 5, so best = 3. Go right.
  • At 6: 6 > 5, so go left.
  • At 4: 4 ≤ 5, so best = 4. Go right.
  • None, so stop. The answer is 4.

ceiling(x) is the smallest key ≥ x. It’s the mirror image of floor. Still, it’s worth tracing it yourself rather than trusting “it’s symmetric”. Trace for ceiling(11):

  • At 8: 8 < 11, so go right.
  • At 10: 10 < 11, so go right.
  • At 14: 14 ≥ 11, so best = 14. Go left.
  • At 13: 13 ≥ 11, so best = 13. Go left.
  • None, so stop. The answer is 13.

Diagram

The floor(5) walk on the worked BSTVisit 8 (greater than 5, go left), 3 (record best 3, go right), 6 (greater than 5, go left), 4 (record best 4, go right), then None: stop, the answer is 4.831016144713NoneLRLRfloor(5): largest key ≤ 5grey: never visited1. 8 > 5: go leftbest None2. 3 ≤ 5: record, go rightbest 33. 6 > 5: go leftbest 34. 4 ≤ 5: record, go rightbest 45. None: stopanswer 4

Implementation

class Node:
    def __init__(self, key, val):
        self.key, self.val = key, val
        self.left = self.right = None


class TreeMap:
    def __init__(self):
        self.root = None

    def put(self, key, val):
        if self.root is None:
            self.root = Node(key, val)
            return
        cur = self.root
        while True:
            if key == cur.key:
                cur.val = val                 # map semantics: existing key, overwrite
                return
            side = "left" if key < cur.key else "right"
            nxt = getattr(cur, side)
            if nxt is None:
                setattr(cur, side, Node(key, val))   # first empty slot on the path
                return
            cur = nxt

    def get(self, key):
        cur = self.root
        while cur:
            if key == cur.key:
                return cur.val
            cur = cur.left if key < cur.key else cur.right
        return None

    def floor(self, x):
        """Largest key <= x, or None."""
        best, cur = None, self.root
        while cur:
            if cur.key > x:
                cur = cur.left        # cur.key and every key in cur.right are > x
            else:
                best = cur.key        # cur.key <= x is valid; anything better is
                cur = cur.right       # in (cur.key, x], so only in cur.right
        return best

    def ceiling(self, x):
        """Smallest key >= x, or None."""
        best, cur = None, self.root
        while cur:
            if cur.key < x:
                cur = cur.right       # cur.key and every key in cur.left are < x
            else:
                best = cur.key        # cur.key >= x is valid; anything better is
                cur = cur.left        # in [x, cur.key), so only in cur.left
        return best


m = TreeMap()
for k in [8, 3, 10, 1, 6, 14, 4, 7, 13]:
    m.put(k, f"v{k}")
m.put(6, "six")
print(m.get(6), m.get(5))            # six None
print(m.floor(5), m.ceiling(11))     # 4 13
print(m.floor(0), m.ceiling(15))     # None None
print(m.floor(8), m.ceiling(8))      # 8 8

The None results test the two cases where there’s no candidate at all. For floor(0), every key is > 0, so the walk only ever goes left and best is never set. For ceiling(15), every key is < 15, so the walk only goes right. On an exact match, both floor and ceiling return the key itself. On an empty map, all three queries return None.

For comparison, here’s the sorted-list version. With keys = [1, 3, 4, 6, 7, 8, 10, 13, 14], keys[bisect.bisect_right(keys, 5) - 1] gives 4, and keys[bisect.bisect_left(keys, 11)] gives 13 (I ran both). When x is below or above every key, those indices fall outside the list, so remember to bounds-check them.

Complexity: get, put, floor and ceiling each take O(h) time. They use O(1) extra space, because they’re loops, not recursion. An in-order walk over all keys is O(n). With bisect on a sorted list, lookups are O(log n), but inserts are O(n) because the list has to shift (recalled).

Recognition

Signals that an ordered map fits: you need “the closest key above/below x”, “the k-th smallest”, “all keys in a range”, or sorted iteration while the collection keeps changing.

When the input is already a BST, the signal is the ordering itself. Any comparison at a node can throw away a whole subtree. So ask yourself: what does one comparison rule out? In this list, Validate Binary Search Tree, Kth Smallest Element In a Bst, and Lowest Common Ancestor of a Binary Search Tree are the problems where the BST property carries the solution.

When NOT to use it:

  • You only need exact-match lookups. Use dict or set.
  • The data never changes. Sort it once, then use bisect.
  • You only ever need the min or the max. A heap (Part 10) is simpler.

Pitfalls

  • Moving on without recording the candidate. In floor, if you forget best = cur.key before going right, you return None or an out-of-date key.
  • Mixing up the directions between floor and ceiling. Test each one on three inputs: an exact match, a value below all keys, and a value above all keys.
  • Assuming a plain BST gives O(log n). The same collapse from module 1 applies when keys arrive in sorted order.
  • Treating Python’s dict order as key order. It’s insertion order (recalled, guaranteed since 3.7).

Active Recall

  1. On the worked BST, what are ceiling(5) and floor(7)? Trace ceiling(5).

  2. In floor, after recording best = cur.key, why is it safe to never look at cur.left again?

  3. With keys = [1, 3, 4, 6, 7, 8, 10, 13, 14], what does bisect.bisect_right(keys, 0) - 1 return, and why is that a bug if used directly as an index?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Judgment call: skipped. Validate Binary Search Tree, Kth Smallest Element In a Bst and Lowest Common Ancestor of a Binary Search Tree each make you reason from the ordering property on your own. So they act as this module’s checkpoint.

Transfer test

A ride-hailing service stores drivers keyed by their current distance from the city centre (distances change as drivers move). Riders ask for “the driver whose distance is closest to mine”. Would you use an ordered map? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Iterative DFS

Foundation

Recursion uses a hidden stack called the call stack. Each function call that hasn’t finished yet sits on it. Iterative DFS replaces that hidden stack with an ordinary Python list that you control. There are two reasons to do this:

  • Depth. CPython’s default recursion limit is 1,000 frames (recalled; sys.getrecursionlimit() printed 1000 here). When I ran the recursive preorder above on a 5,000-node chain, it raised RecursionError. The iterative version handled it fine.
  • Control. With your own stack, you can pause after any node and resume later. You can also stop early without having to unwind a pile of function calls.

Mechanics

We’ll use the same worked tree as in DFS and BFS.

Preorder is the easy one. Pop a node, visit it, then push its children. Push the right child first. A stack is last-in-first-out, so the left child, pushed last, is the one popped next. That way the whole left subtree gets explored before the right child comes off the stack.

The invariant here is: the stack holds exactly the subtrees that still need visiting, in the reverse of the order they’ll be visited.

Inorder is trickier, because a node has to wait until its whole left subtree is done. Here’s the pattern:

  1. From the current node, walk down to the left as far as you can, pushing every node on the way. This chain of left children is called the left spine.
  2. Pop one node. Its left subtree is now finished, because everything pushed after it has already been popped. So visit it now.
  3. Move to its right child and repeat.

The loop runs while cur or stack. cur is a subtree you haven’t started yet. stack holds nodes waiting to be visited. You’re only done when both are empty.

Carrying state. In recursive top-down DFS, you pass state down as arguments. Iteratively, you push a tuple (node, state) instead, so each node carries its own copy. For example, (node, running_sum).

Postorder has a neat trick. Do a preorder that visits root, then right, then left, and reverse the output. On the worked tree, root, right, left gives 1, 3, 6, -2, -5, 4. Reversed, that’s 4, -5, -2, 6, 3, 1, which is the postorder from the DFS module.

Diagram

Iterative preorder: stack after each pop and pushPop 1, stack [3, -2]; pop -2, stack [3, -5, 4]; pop 4, stack [3, -5]; pop -5, stack [3]; pop 3, stack [6]; pop 6, stack empty. Output 1 -2 4 -5 3 6.iterative preorder: pop, push right then leftpopstack after pushblue = topoutput so far13-21-23-541 -243-51 -2 4-531 -2 4 -5361 -2 4 -5 36empty1 -2 4 -5 3 6
Iterative inorder: stack after each popPush the left spine 1, -2, 4. Pop 4, stack [1, -2]; pop -2, stack [1]; push and pop -5, stack [1]; pop 1, empty; push and pop 3, empty; push and pop 6, empty. Output 4 -2 -5 1 3 6.iterative inorder: push left spine, pop, go rightpopstack after popblue = topoutput so far41-24-214 -2-514 -2 -51empty4 -2 -5 13empty4 -2 -5 1 36empty4 -2 -5 1 3 6

In the inorder trace, 1, -2 and 4 are pushed before the first pop. Those three are the left spine. After -2 is popped, cur moves to -5. It gets pushed and popped straight away, because it has no left child.

Implementation

def preorder_iter(root):
    out = []
    stack = [root] if root else []
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.right:
            stack.append(node.right)   # pushed first, popped after the whole left subtree
        if node.left:
            stack.append(node.left)    # pushed last, popped next (LIFO)
    return out


def inorder_iter(root):
    out, stack, cur = [], [], root
    while cur or stack:
        while cur:                     # push the whole left spine of cur
            stack.append(cur)
            cur = cur.left
        node = stack.pop()             # every node in node.left is already in out
        out.append(node.val)
        cur = node.right               # next: the right subtree of node
    return out


def root_to_leaf_iter(root):
    sums = []
    stack = [(root, 0)] if root else []
    while stack:
        node, running = stack.pop()    # each entry carries its own running total
        running += node.val
        if node.left is None and node.right is None:
            sums.append(running)
        if node.right:
            stack.append((node.right, running))
        if node.left:
            stack.append((node.left, running))
    return sums


print(preorder_iter(sample()))      # [1, -2, 4, -5, 3, 6]
print(inorder_iter(sample()))       # [4, -2, -5, 1, 3, 6]
print(root_to_leaf_iter(sample()))  # [3, -6, 10]

All three match the recursive outputs from the DFS module. Edge cases I ran:

  • An empty tree gives [] for all three.
  • A single node 9 gives [9].
  • A 5,000-deep left chain returns all 5,000 values from both preorder_iter and inorder_iter, with no error. (Inorder starts 0, 1, 2, from the bottom of the chain.)

Complexity: O(n) time. Stack space is O(h) for inorder, and for the chain-shaped trees above. Preorder’s stack can hold one waiting right child per level, plus the current node’s children. For a binary tree that’s still O(h).

Recognition

Signals that iterative DFS fits:

  • The tree may be very deep. Think degenerate or adversarial inputs, like n up to 10^5 arranged as a chain.
  • You need to pause a traversal and resume it later.
  • You want to stop early once you’ve found what you need, without unwinding the recursion.

Otherwise, recursion is shorter and interviewers accept it. A good move is to say out loud that deep inputs could hit the recursion limit, then offer the iterative version.

In this list, every problem can be solved recursively. Kth Smallest Element In a Bst is the one where knowing the iterative version gives you a real alternative.

How does it differ from BFS? It’s the same loop shape with a different container. A stack gives you depth-first, and a queue gives you breadth-first.

Pitfalls

  • Pushing left before right in preorder. You get root, right, left instead.
  • Using while stack: alone as the inorder loop condition. It exits too early, twice. At the start, the stack is empty but cur is the root. Later, after the root is popped, the stack is empty again while the root’s right subtree hasn’t been visited yet.
  • Forgetting cur = node.right after visiting. You either loop forever on the same left spine or skip right subtrees.
  • Sharing one mutable state object across stack entries, like a single list for the current path. Push a copy or an immutable value instead.
  • Raising sys.setrecursionlimit as a “fix”. It just moves the crash to the C stack, which can kill the interpreter (recalled). An explicit stack is the real fix.

Active Recall

  1. In inorder_iter on the worked tree, what’s on the stack right after 4 is popped, and why can 4 be visited then?

  2. Why does inorder_iter need cur at all, when preorder_iter works with just the stack?

  3. How would you turn preorder_iter into postorder without a visited flag?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Judgment call: included. Every problem in this list can be solved with recursion, so you’d otherwise never practise the explicit-stack mechanics on their own.

Design a class that takes the root of a BST and offers has_next() and next(). Each call to next() returns the next key in ascending order. The tree may have 10^5 nodes. Your class may use O(h) memory, where h is the height, but not O(n). So copying all keys into a list up front is not allowed. On the worked BST from module 1, repeated next() calls return 1, 3, 4, 6, 7, 8, 10, 13, 14.

Before any code, write down four things: the observation, the approach, why it’s correct, and the complexity.

Work it out, then talk it through withChatGPT ↗Claude ↗

Transfer test

You’re writing a tool that walks a directory tree to total file sizes. Some generated build folders nest 20,000 levels deep. Would you use iterative DFS? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Integration

How the five connect to trees. Every tree problem makes two decisions.

  1. What order do I visit nodes in? Depth-first is the default: recursive normally, iterative when depth or pausing matters. Breadth-first is for when levels or nearness matter.
  2. Which way does information flow? Down as arguments, up as return values, or both, with a separate variable holding the answer.

The two BST modules add a third question: does the ordering let me skip subtrees? If it does, a problem that looks like “visit everything” turns into “walk one path”, which is O(h).

Telling the approaches apart:

If the problem… Reach for Why
needs a node’s answer from its children’s answers recursive DFS, postorder children must finish first
passes a constraint or running value from root toward leaves recursive DFS, preorder-style arguments each path carries its own state
talks about levels, rows, “leftmost/rightmost per level”, or nearest BFS with a level-size loop the queue separates levels
is on a BST and asks about keys, ranks or ranges walk using the ordering (plus inorder = sorted) one comparison discards a subtree
may be thousands deep, or must pause/stop early iterative DFS your stack, your control
compares two trees DFS on both in lockstep the same recursion shape on a pair of nodes

Pairs that are easy to mix up:

  • DFS vs BFS. Both take O(n) time. BFS memory grows with the tree’s width, DFS memory with its height. Choose by the order the problem cares about.
  • Recursive vs iterative DFS. Same order, same complexity. The iterative version only buys you safety on deep trees, plus control over pausing and stopping.
  • General-tree reasoning vs BST reasoning. If the problem says BST and your solution never compares against a node’s key, you’re probably ignoring the property that makes it easy.

Recognition checklist for an unfamiliar tree problem:

  1. Is it a BST? If yes, what does one comparison at a node rule out?
  2. What does a node need from its children? If anything, that’s a postorder return value. Write down what it means in one sentence.
  3. What does a node need from its ancestors? If anything, pass it down as an argument.
  4. Is the returned value the same as the final answer? If not, keep the answer in a separate variable.
  5. Does the problem mention levels, rows, or “nearest”? If so, use BFS with size = len(queue).
  6. What does None return? Check that it doesn’t break a max, min or sum at the parent.
  7. How deep can the tree be? If a chain of 10^4 or more nodes is allowed, mention the recursion limit and have the iterative version ready.
  8. Is the input given as traversal sequences rather than nodes? Remember which traversals pin down a tree’s shape and which don’t.

The problems

Solve these with the cycle from the method. Give each problem a 15-minute honest struggle. Once it clicks, write the key insight in one sentence. Then review it with spaced repetition.

For trees, spend the struggle on two questions:

  • Can I combine results from the left and right subtrees?
  • Can I rebuild the call stack by hand on a three- or four-node example, and explain how information flows from the leaves up to the root?

Take this lesson as a live session

To be taught this interactively instead, with the coach waiting for your answers at every checkpoint, open the full lesson prompt, already filled in for trees:

Open the full lesson inChatGPT ↗Claude ↗