Kodewick
Start learning →
Patterns: trees29 / 52

Patterns: trees

Lesson 29 of 52 · Part 5 · Trees and heaps · about 20 minutes

This chapter 4 review covers three binary-tree patterns: passing information down as parameters or handing answers up as return values, the lowest common ancestor, and level-by-level BFS with a deque, each visiting every node once, O(n).

There are hundreds of binary tree problems: maximum depth, path sum, checking balance, diameter, lowest common ancestor, right side view, zigzag order… but nearly all of them are written with three patterns. One recursive function either passes information down from the top as parameters (how much so far, which depth this is), or hands answers up from the bottom as return values (how tall my subtree is, whether I found it); and whatever needs "one level at a time" uses a BFS with a deque, noting how many are in this level before the loop. All three visit each node once: O(n) time, with an O(h) stack for recursion and a queue of O(the widest level) for BFS.

Pattern 1: top-down or bottom-up

The same question, "maximum depth", can be written two ways:

  • Bottom-up: my depth = 1 + the larger of my two children's depths. Information goes up through return values; lesson 1's height is like this.
  • Top-down: on reaching a node, pass "the level I am on" to the children as a parameter; on reaching a leaf, use it to update a global answer.

Problems about "a path from the root to a leaf" suit top-down naturally: the parameter carries "the sum from the root to here" or "how much is still missing". Take path sum (LeetCode 112): is there a path from the root to a leaf whose values add up to 22?

5
4
11
7
2
8
13
4
1

Set off from the root carrying 22 and subtract each node's value on the way down; reach a leaf at exactly 0 and you have found 5 → 4 → 11 → 2
main.py
1from collections import deque2 3class TreeNode:4    def __init__(self, val, left=None, right=None):5        self.val = val6        self.left = left7        self.right = right8 9def build(vals):10    if not vals or vals[0] is None:11        return None12    root = TreeNode(vals[0])13    q = deque([root])14    i = 115    while q and i < len(vals):16        node = q.popleft()17        if vals[i] is not None:18            node.left = TreeNode(vals[i])19            q.append(node.left)20        i += 121        if i < len(vals) and vals[i] is not None:22            node.right = TreeNode(vals[i])23            q.append(node.right)24        i += 125    return root26 27def depth_up(node):                        # bottom-up: return values build the answer28    if node is None:29        return 030    return 1 + max(depth_up(node.left), depth_up(node.right))31 32def depth_down(root):                      # top-down: a parameter carries the depth33    best = 034    def go(node, d):35        nonlocal best36        if node is None:37            return38        if node.left is None and node.right is None:39            best = max(best, d)            # at a leaf: update the answer40        go(node.left, d + 1)41        go(node.right, d + 1)42    go(root, 1)43    return best44 45def path_sums(root):                       # every root-to-leaf path: a parameter carries the sum so far46    out = []47    def go(node, s):48        if node is None:49            return50        s += node.val51        if node.left is None and node.right is None:52            out.append(s)53        go(node.left, s)54        go(node.right, s)55    go(root, 0)56    return out57 58root = build([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1])59print(depth_up(root), depth_down(root))60print(path_sums(root))
Output
4 4
[27, 22, 26, 18]

The four root-to-leaf paths sum to 27, 22, 26 and 18; the second is the 22. Which direction to choose depends on what the answer needs:

Top-downBottom-up
How information movesparameters, from the root to the leavesreturn values, from the leaves to the root
Where the answer isupdated globally at the leaves (nonlocal), or True returned directlythe value the root gets back
Good forpath sum, root-to-leaf paths, checking a BST with boundsheight, size, balance, diameter, lowest common ancestor
How to write itgo(node, the state on arriving here)get both sides' results first, then work out your own
Choose one

Which of these problems suits "top-down", carrying state down as a parameter, best?

Exercise 1

Path sum

Complete has_path_sum(node, target): is there a path from the root to a leaf whose values add up to target? Top-down: on the way down, subtract the current value from target.

It should print
True True False
False False
exercise1.py
1from collections import deque2 3class TreeNode:4    def __init__(self, val, left=None, right=None):5        self.val = val6        self.left = left7        self.right = right8 9def build(vals):10    if not vals or vals[0] is None:11        return None12    root = TreeNode(vals[0])13    q = deque([root])14    i = 115    while q and i < len(vals):16        node = q.popleft()17        if vals[i] is not None:18            node.left = TreeNode(vals[i])19            q.append(node.left)20        i += 121        if i < len(vals) and vals[i] is not None:22            node.right = TreeNode(vals[i])23            q.append(node.right)24        i += 125    return root26 27def has_path_sum(node, target):28    # empty tree: False; a leaf checks target == node.val; otherwise search both sides with target - node.val29    return False30 31root = build([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1])32print(has_path_sum(root, 22), has_path_sum(root, 26), has_path_sum(root, 9))33print(has_path_sum(build([1, 2]), 1), has_path_sum(None, 0))
Output
Press Run or Ctrl+Enter

Pattern 2: the lowest common ancestor

The lowest common ancestor (LCA) of two nodes p and q is the node that is an ancestor of both and closest to them (a node counts as its own ancestor). It is a typical bottom-up problem (LeetCode 236): each node asks its two subtrees "did you find p or q?", and returns the node found, or None if nothing was found.

  • If I am p or q: return myself, no need to search further down.
  • If both sides hand up a node: p and q are on different sides, and I am the answer.
  • If only one side hands one up: pass it on up unchanged.
3
5
6
2
7
4
1
0
8

The lowest common ancestor of 6 and 4: each node returns "the one found in my subtree"; 5's left and right each hand one up, so 5 is the answer
main.py
1from collections import deque2 3class TreeNode:4    def __init__(self, val, left=None, right=None):5        self.val = val6        self.left = left7        self.right = right8 9def build(vals):10    if not vals or vals[0] is None:11        return None12    root = TreeNode(vals[0])13    q = deque([root])14    i = 115    while q and i < len(vals):16        node = q.popleft()17        if vals[i] is not None:18            node.left = TreeNode(vals[i])19            q.append(node.left)20        i += 121        if i < len(vals) and vals[i] is not None:22            node.right = TreeNode(vals[i])23            q.append(node.right)24        i += 125    return root26 27def find(node, val):28    if node is None or node.val == val:29        return node30    return find(node.left, val) or find(node.right, val)31 32def lca(node, p, q):33    if node is None or node is p or node is q:34        return node35    left = lca(node.left, p, q)36    right = lca(node.right, p, q)37    if left and right:                     # one found on each side38        return node39    return left or right                   # only one side: pass it on up40 41root = build([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])42for a, b in [(6, 4), (7, 8), (5, 4), (0, 8)]:43    print(a, b, "->", lca(root, find(root, a), find(root, b)).val)
Output
6 4 -> 5
7 8 -> 3
5 4 -> 5
0 8 -> 1

The third pair, (5, 4): reaching 5 returns at once, without ever looking for 4 below it. Is that right? The problem guarantees both p and q are in the tree; 4 is not outside 5, so it must be below 5, which makes 5 the answer.

The test is node is p (the same node), not equal values: a tree may repeat values. If the tree is a binary search tree, there is a faster walk: if p and q are both smaller than the current node go left, if both larger go right, otherwise the current node is the answer; one path only, O(h).

Choose one

Use the tree in this step's picture (root 3, left subtree 5, right subtree 1). What are lca(7, 0) and lca(6, 7)?

Exercise 2

The lowest common ancestor in a BST

Complete lca_bst(root, p, q) (p and q are values, both in the tree): use smaller-left, larger-right and walk a single path down from the root. If p and q are both smaller than the current node go left, if both larger go right, otherwise the current node is the answer. Return its value.

It should print
6 4 2 8
exercise2.py
1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert(node, x):8    if node is None:9        return TreeNode(x)10    if x < node.val:11        node.left = insert(node.left, x)12    else:13        node.right = insert(node.right, x)14    return node15 16def lca_bst(root, p, q):17    node = root18    # a while loop: both smaller go left, both larger go right, otherwise return node.val19    return None20 21root = None22for x in [6, 2, 8, 0, 4, 7, 9, 3, 5]:23    root = insert(root, x)24print(lca_bst(root, 2, 8), lca_bst(root, 3, 5), lca_bst(root, 2, 4), lca_bst(root, 7, 9))
Output
Press Run or Ctrl+Enter

Pattern 3: one level at a time

Lesson 2's level order takes out one node at a time and can't tell which level each is on. For "the last of each level" (right side view, LeetCode 199), "each level's average" (LeetCode 637) or "each level on its own line" (LeetCode 102), note how many are in the queue right now as each level starts: they are exactly that level's nodes, for _ in range(len(q)) takes out only that many, and their children all queue behind them for the next level.

1
2
4
5
7
3
6

As each level starts, the queue holds exactly that level's nodes; the last one out of each level is what you see looking from the right
main.py
1from collections import deque2 3class TreeNode:4    def __init__(self, val, left=None, right=None):5        self.val = val6        self.left = left7        self.right = right8 9def build(vals):10    if not vals or vals[0] is None:11        return None12    root = TreeNode(vals[0])13    q = deque([root])14    i = 115    while q and i < len(vals):16        node = q.popleft()17        if vals[i] is not None:18            node.left = TreeNode(vals[i])19            q.append(node.left)20        i += 121        if i < len(vals) and vals[i] is not None:22            node.right = TreeNode(vals[i])23            q.append(node.right)24        i += 125    return root26 27def levels(root):28    out = []29    q = deque([root] if root else [])30    while q:31        level = []32        for _ in range(len(q)):           # only this level's nodes33            node = q.popleft()34            level.append(node.val)35            if node.left:36                q.append(node.left)37            if node.right:38                q.append(node.right)39        out.append(level)40    return out41 42root = build([1, 2, 3, 4, 5, None, 6, None, None, 7])43lv = levels(root)44print(lv)45print("right side view", [level[-1] for level in lv])46print("left side view ", [level[0] for level in lv])
Output
[[1], [2, 3], [4, 5, 6], [7]]
right side view [1, 3, 6, 7]
left side view  [1, 2, 4, 7]

range(len(q)) works out its count when the loop starts, so children added to q inside the loop are not counted in this level. With "one list per level", the right side view, the left side view, each level's maximum and zigzag order (reverse the odd levels) differ only in the last line.

PatternTypical problemsTimeExtra space
Top-down (parameters)path sum, root-to-leaf paths, validate a BSTO(n)O(h)
Bottom-up (return values)height, balance, diameter, lowest common ancestorO(n)O(h)
Level-by-level BFSlevel order by line, right side view, level averages, minimum depthO(n)O(the widest level)

In interviews: faced with a tree problem, first ask whether the answer wants "a path from the root" (top-down), "a value summed up from each subtree" (bottom-up), or "by levels" (BFS). Once written, walk through it with an empty tree, a root alone and a line. "Minimum depth" is a trap: a node with only one child is not a leaf, so you can't take min with the 0 from its None side; BFS stopping at the first leaf is the safest.

Guess the outputA wrong guess is fine

The last node to leave the queue on each level is the right view. 4 is in the left subtree. What does this print?

1from collections import deque2 3class TreeNode:4    def __init__(self, val, left=None, right=None):5        self.val = val6        self.left = left7        self.right = right8 9root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))10q = deque([root])11right = []12while q:13    n = len(q)14    for i in range(n):15        node = q.popleft()16        if i == n - 1:17            right.append(node.val)18        if node.left:19            q.append(node.left)20        if node.right:21            q.append(node.right)22print(right)
Exercise 3

Level averages

Complete averages(root): return a list of the average value on each level. Use a deque, and note len(q) as each level starts.

It should print
[3.0, 14.5, 11.0]
[1.0, 2.5, 4.0]
[]
exercise3.py
1from collections import deque2 3class TreeNode:4    def __init__(self, val, left=None, right=None):5        self.val = val6        self.left = left7        self.right = right8 9def averages(root):10    out = []11    q = deque([root] if root else [])12    # each level: take out len(q) nodes, add them up and divide by the count; children join at the back13    return out14 15root = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))16print(averages(root))17print(averages(TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3))))18print(averages(None))
Output
Press Run or Ctrl+Enter

How you write it at work

At work you rarely meet a TreeNode; much more often a tree that already exists: directories, nested JSON, an org chart, threads of comment replies. The three patterns apply just the same, only the children change from left and right to a list:

main.py
1from collections import deque2 3org = {"name": "CEO", "kids": [4    {"name": "CTO", "kids": [{"name": "Backend", "kids": []}, {"name": "Frontend", "kids": []}]},5    {"name": "CFO", "kids": [{"name": "Accounts", "kids": []}]},6]}7 8def depth(node):                           # bottom-up: how many levels deep9    return 1 + max((depth(k) for k in node["kids"]), default=0)10 11def paths(node, prefix, out):              # top-down: carrying the path from the root12    path = prefix + [node["name"]]13    if not node["kids"]:14        out.append(" / ".join(path))15    for k in node["kids"]:16        paths(k, path, out)17    return out18 19def by_level(root):                        # by levels20    q, out = deque([root]), []21    while q:22        out.append([n["name"] for n in q])23        for _ in range(len(q)):24            q.extend(q.popleft()["kids"])25    return out26 27print(depth(org))28print(paths(org, [], []))29print(by_level(org))
Output
3
['CEO / CTO / Backend', 'CEO / CTO / Frontend', 'CEO / CFO / Accounts']
[['CEO'], ['CTO', 'CFO'], ['Backend', 'Frontend', 'Accounts']]
  • When the children are a list, max(..., default=0) handles a node with no children.
  • When the data may be very deep (comment threads where people can reply forever), switch to your own stack or deque instead of recursion.
  • To find "the lowest common ancestor of two nodes" when there are parent pointers (say every directory knows its parent), it is simpler still: put all of one node's ancestors in a set, then walk up from the other node; the first one found in the set is the answer.
Guess the outputA wrong guess is fine

A tree that keeps its children in a list: with no children, max uses default=0. What does this print?

1def depth(node):2    return 1 + max((depth(k) for k in node["kids"]), default=0)3 4leaf = {"kids": []}5tree = {"kids": [leaf, {"kids": [leaf, {"kids": []}]}]}6print(depth(leaf), depth(tree))

Summary

Take-away

Three patterns for trees

  • Top-down: pass the state to the children as a parameter; decide or update the answer at the leaves
  • Bottom-up: get both sides' return values first, then put your own together
  • Lowest common ancestor: if both sides hand up a node, you are the answer; in a BST walk one path only
  • By levels: as each level starts, n = len(q), and take out only n
  • All O(n); recursion stack O(h), BFS queue O(the widest level)
1def go(node, state):                 # top-down2    ...go(node.left, new_state)3left, right = f(node.left), f(node.right)   # bottom-up4for _ in range(len(q)):              # by levels5    node = q.popleft()

Chapter 4 quick check

Five questions: height by recursion, traversal orders, deleting from a BST, what heapq's list looks like, and Huffman's total bits. Work out what each prints first, then pick an option.

Guess the outputA wrong guess is fine

2 has only a right child 3, and 3 has only a left child 4. What does it print?

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def f(node):8    if node is None:9        return 010    return 1 + max(f(node.left), f(node.right))11 12root = TreeNode(1, TreeNode(2, None, TreeNode(3, TreeNode(4))), TreeNode(5))13print(f(root), f(root.right))
Guess the outputA wrong guess is fine

The tree is written as tuples: (value, left, right). What do preorder and inorder print?

1def pre(node):2    if node:3        yield node[0]4        yield from pre(node[1])5        yield from pre(node[2])6 7def ino(node):8    if node:9        yield from ino(node[1])10        yield node[0]11        yield from ino(node[2])12 13t = (1, (2, (4, None, None), (5, None, None)), (3, None, None))14print(list(pre(t)), list(ino(t)))
Guess the outputA wrong guess is fine

Insert 5 3 8 6 9 7 in turn, then delete the root 5. What does preorder print?

1class TreeNode:2    def __init__(self, val, left=None, right=None):3        self.val = val4        self.left = left5        self.right = right6 7def insert(node, x):8    if node is None:9        return TreeNode(x)10    if x < node.val:11        node.left = insert(node.left, x)12    else:13        node.right = insert(node.right, x)14    return node15 16def delete(node, x):17    if node is None:18        return None19    if x < node.val:20        node.left = delete(node.left, x)21    elif x > node.val:22        node.right = delete(node.right, x)23    else:24        if node.left is None:25            return node.right26        if node.right is None:27            return node.left28        succ = node.right29        while succ.left:30            succ = succ.left31        node.val = succ.val32        node.right = delete(node.right, succ.val)33    return node34 35def pre(node):36    return [node.val] + pre(node.left) + pre(node.right) if node else []37 38root = None39for x in [5, 3, 8, 6, 9, 7]:40    root = insert(root, x)41root = delete(root, 5)42print(pre(root))
Guess the outputA wrong guess is fine

heappush 4 1 3 2 in turn, then heappop once. What does it print?

1import heapq2 3h = []4for x in [4, 1, 3, 2]:5    heapq.heappush(h, x)6x = heapq.heappop(h)7print(x, h)
Guess the outputA wrong guess is fine

Three letters appear 3 times each, and a Huffman tree is built. What are the total bits (the sum of the merged weights)?

1import heapq2 3h = [3, 3, 3]4heapq.heapify(h)5cost = 06while len(h) > 1:7    w = heapq.heappop(h) + heapq.heappop(h)8    cost += w9    heapq.heappush(h, w)10print(cost)