iq.lab
Python starts when a code cell comes near or you run one
08 Recursion and trees

Lesson 2 of 5

Binary trees

A binary tree is a set of nodes in which each node points at up to two children. Visit every node in preorder, inorder or postorder with a short recursive function, visit it in preorder with a stack of your own, and answer most tree questions by building each node's answer from its children's answers.

About 1 hour 45 minutes, with the 3 problems worked in it
By the end you can
  • Build a tree by hand with TreeNode, and from a level-order list with build_tree

  • Write preorder, inorder and postorder as recursive functions, and say where each one writes the node

  • Write preorder without recursion, using a list as a stack

  • Solve a tree problem by deciding what an empty tree returns and how a node combines its children's answers

  • State the cost of a tree walk, O(n) time and O(h) extra space, where h is the number of levels

Your data warehouse has an employees table with a manager_id column. Each row points at its manager, and the row at the top, the CEO, has a manager_id of NULL. That table describes a tree: one item at the top, and under each item, the items that hang from it. How long is the longest reporting chain?

In an interview the tree arrives as objects linked by pointers, with the same kind of question: how deep is it, are two trees the same, list the values in some order. Most of these questions are answered by one short recursive function that asks the same question at every node. This lesson builds that function from the ground up.

A node with two children

What is a tree, in Python?

A binary tree is built from nodes, and each node has at most two children. A node is a small object with three fields: val, the value it holds; left, its left child; and right, its right child. A missing child is None. Here is the whole class:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val        # the value this node holds
        self.left = left      # the left child, or None
        self.right = right    # the right child, or None

Every code cell in this lab already has this class, so you never type it, and LeetCode shows the same class in a comment above its tree problems. It is the linked list's ListNode with next replaced by left and right.

You hold a tree by its top node, the root. Following left and right from the root reaches every node. An empty tree has no nodes, so its root is None. The trace builds a four-node tree by hand. On the right, under "Tree", each node is a circle with its value, a line joins each node to its children, and a name that points at a node shows as a tag above it. Before you step through, guess what the last line prints.

Step throughFour nodes, linked by hand
Step 1 of 6
Line 1 is about to run.
A new node holding 1. Both of its children are None for now.
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.right = TreeNode(4)
print(root.left.val, root.left.left, root.left.right.val)
Names
no names yet
Output
(nothing printed yet)

Trees come with a few words, and every tree lesson uses them. In the tree you built:

  • 1 is the root, the one node that no other node points at.
  • 2 and 3 are the children of 1, and 1 is their parent. 4 is the right child of 2.
  • 3 and 4 are leaves: nodes with no children.
  • The subtree of 2 is the 2 together with everything below it, here the 2 and the 4. Every node is the root of its own subtree, so a function that works on a whole tree also works on every subtree.
  • A level is all the nodes the same number of steps below the root: 1 is on level 1, 2 and 3 on level 2, 4 on level 3.
  • The number of levels is the tree's height, written h. This tree has h = 3. (Some books count the links instead of the nodes, which gives one less. In an interview, say which one you mean.)

A tree written as a list

Typing root.left.right = TreeNode(4) for every node gets slow. Tests, examples and LeetCode write a tree as one list instead. How does a list describe a tree?

build_tree reads the list in level order: the root, then each level from left to right, with None where a child is missing. After the root, every real node takes the next two values as its children, left then right, in the order the nodes appear. The tree you built by hand is build_tree([1, 2, 3, None, 4]):

Position in the listValueBecomes
01the root
12left child of 1
23right child of 1
3Noneleft child of 2: missing
44right child of 2

The list ends when the values run out, so 3 and 4 get no children. A None takes no values for children: a missing node cannot have any. An empty list is the empty tree: build_tree([]) returns None. LeetCode writes the same lists with null where Python has None: [1,2,3,null,4].

The lab's tree_values(root) goes the other way, from a tree back to the list, without the Nones at the end. The trace builds two trees; the second list has a None in the root's left slot. Before you step through, sketch the second tree from its list.

Step throughTwo lists, two trees
Step 1 of 5
Line 1 is about to run.
The tree you built by hand, from one list.
first = build_tree([1, 2, 3, None, 4])
second = build_tree([1, None, 2, None, 3])
print(tree_values(first))
print(tree_values(second))
Names
no names yet
Output
(nothing printed yet)

Now draw one yourself. This is the skill you need to read every example in this module.

On paperFrom a list to a tree

On paper, draw the tree that build_tree([6, 2, 9, None, 4, 7, None, 3]) builds. Then count its leaves, the nodes with no children.

The rule: after the root, every real node takes the next two values as its children, left then right, in level order. A None takes no values.

Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

leaves

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Three orders for visiting every node

How do you visit every node of a tree? Visiting every node once, in some order, is called a traversal. A list has one natural order, left to right. A tree offers a choice at every node: the node itself, its left subtree, its right subtree. Which comes first?

The walk is recursive. A recursive function calls itself on a smaller input. From the recursion lesson: handle the smallest input directly (the base case), and for anything bigger, trust that the call on a smaller input works (the leap of faith). For a tree, the smaller inputs are the two subtrees and the base case is the empty tree, None. One way to visit a tree: if it is empty, do nothing; otherwise write the node, then visit its left subtree, then its right subtree.

The trace writes the values of build_tree([1, 2, 3, None, 4]) into a list out. The helper visit lives inside preorder, so every call adds to the same out. Each call gets its own box on the right, and the boxes pile up as calls start inside calls: this pile is the call stack from the recursion lesson, the calls that have started and not yet returned. Before you step through, guess the order in which the four values land in out.

Step throughPreorder, one call per node
Step 1 of 42
Line 1 is about to run.
def preorder(root):
out = []
def visit(node):
if node is None:
return
out.append(node.val)
visit(node.left)
visit(node.right)
visit(root)
return out
Names
no names yet
Output
(nothing printed yet)

How big is h? It depends on the shape. In a chain, where every node has one child, each node sits on its own level, so h = n. When every level is full, each level holds twice as many nodes as the one above: 1, 2, 4, 8. Four full levels hold 15 nodes, and h is about log₂ n: a million nodes packed this way need only 20 levels. The same walk goes about 20 calls deep on the packed tree and a million calls deep on the chain.

Where the write happens decides the order. Move out.append(node.val) and you get the other two classic orders. The calls run in exactly the same sequence; only the moment of writing changes:

  • Preorder writes the node, then its left subtree, then its right subtree: 1, 2, 4, 3.
  • Inorder writes the left subtree, then the node, then the right subtree: 2, 4, 1, 3. On a binary search tree, the last lesson of this module, inorder lists the values from smallest to largest.
  • Postorder writes the left subtree, then the right subtree, then the node: 4, 2, 3, 1.

Here are the other two as code. Each is the traced preorder with one line moved. Run it, then move the append in inorder above visit(node.left) and run it again: you get preorder back.

⌘+Enter runs · edit freelyPython starts when a code cell comes near or you run one

It prints [2, 4, 1, 3] and [4, 2, 3, 1], the two lists above.

All three are depth-first: they go all the way down one branch before they come back for the next. The instrument below runs all three orders on a bigger tree, build_tree([1, 2, 3, 4, 5, None, 6]). The node being visited is blue, and visited nodes turn lime with their visit number. Under the tree, the Output row grows in visit order, and the Open calls row lists the calls that have started and not yet returned, root first.

Recap: one recursive function visits every node, and where it writes the node picks the order. Its base case is the empty tree, and the call stack remembers the way back up. Writing before the two calls gives preorder, between them inorder, after them postorder. Try one on a new tree:

PredictPostorder on a new tree

This is the trace's walk with the write moved to the end, and it prints each value instead of appending it. Type exactly what it prints, one value per line.

def post(node):
    if node is None:
        return
    post(node.left)
    post(node.right)
    print(node.val)

post(build_tree([5, 3, 8, None, 4]))
Work it outHow many calls?

visit runs once for every node and once for every missing child. How many times is visit called when preorder walks build_tree([1, 2, 3, 4, 5, 6, 7]), a tree of 7 nodes with all 3 levels full? Type a whole number.

calls

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Postorder matters most for the rest of this lesson, because it is the only one of the three that visits a node after both of its children are done:

Quick checkWhich order for subtree totals?

Each node of a tree holds a cost. You want every node's subtree total: its own cost plus the costs of everything below it. A node's total is its own cost plus its two children's totals. In which order must the walk visit the nodes so that each total can be computed at the moment its node is visited?

Choose one answer, then check.

Preorder with a stack of your own

The recursive walk keeps its notebook in the call stack, and, as the recursion lesson showed, Python limits how deep the call stack can grow: plain Python stops at about 1,000 nested calls by default with a RecursionError, and this lab allows 5,000. A chain of 100,000 nodes has h = 100,000, so the walk needs more than 100,000 calls inside each other. So a follow-up may ask you to write the walk without recursion.

Keep the waiting work in a list of your own, used as a stack: last in, first out, append to push onto the top and pop() to take from the top. For preorder: take the top node, write it, then push its children. Push the right child first and the left child second, so the left one is on top and comes out next. The trace draws the stack top first. Before you step through, guess what the stack holds right after the 1 is written and its children are pushed.

Step throughPreorder with a stack of your own
Step 1 of 31
Line 1 is about to run.
def preorder_iter(root):
if root is None:
return []
out = []
stack = [root]
while stack:
node = stack.pop()
out.append(node.val)
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
return out
Names
no names yet
Output
(nothing printed yet)

An empty tree needs the check on line 2. Without it, the stack would start as [None], and line 8 would read None.val and fail with an AttributeError.

The order of the two pushes is the whole trick. Swap them and see what comes out:

PredictPush the left child first

This version pushes the left child before the right one. Type exactly what it prints.

def preorder_iter(root):
    out = []
    stack = [root]
    while stack:
        node = stack.pop()
        out.append(node.val)
        if node.left is not None:
            stack.append(node.left)
        if node.right is not None:
            stack.append(node.right)
    return out

print(preorder_iter(build_tree([1, 2, 3, None, 4])))

Inorder and postorder work with a stack too, with more bookkeeping. The binary search trees lesson, the last in this module, builds inorder that way.

Answers from your children

Visiting nodes is half of tree work. The other half is computing something: how many nodes, how deep, the largest value. Each is one question asked at every node: what is my answer, given my children's answers?

Take counting. If a node's left subtree has 2 nodes and its right subtree has 1, the subtree under the node has 1 + 2 + 1 = 4 nodes. An empty tree has 0. That is the whole function. Each call returns its answer to the call that made it, so the answers travel up the tree. Before you step through, guess what the call on the 2 returns.

Step throughCounting nodes, answers coming up
Step 1 of 37
Line 1 is about to run.
def count_nodes(node):
if node is None:
return 0
left_count = count_nodes(node.left)
right_count = count_nodes(node.right)
return 1 + left_count + right_count
Names
no names yet
Output
(nothing printed yet)

Some problems need a second base case. Counting leaves stops at a leaf, and the None check must come first:

Put in orderCount the leaves

Put the lines in order to build count_leaves(node), which returns how many leaves (nodes with no children) the tree under node has. Indentation is already part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • if node.left is None and node.right is None:
    • def count_leaves(node):
    • return 1 + count_leaves(node.left) + count_leaves(node.right)
    • return 1
    • if node is None:
    • return count_leaves(node.left) + count_leaves(node.right)
    • return 0
    • if node.left is None or node.right is None:

    The base case must be a value that cannot spoil the answer. For a count or a sum, 0 works. For a maximum, 0 does not, as module 1 showed with a running maximum:

    Code itThe largest value in a tree

    Write largest_value(root), which returns the largest value in a non-empty tree. Use recursion, not a list of all the values: decide what an empty subtree returns, and how a node combines its own value with its children's answers. Then press Watch it run to see the answers come up.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Now the classic. The depth of a tree, or maximum depth, is the number of nodes on its longest path from the root down to a leaf, and an empty tree has depth 0. It is the height h from the first section, now worked out by code. Ask the two questions: what does None return, and how does a node turn a left depth and a right depth into its own? Try it before you open the hints.

    easyTrees, depth-firstRecursion target 15 min

    Maximum depth of a binary tree

    You get the root of a binary tree: a TreeNode with a value val and two children, left and right, each another TreeNode or None. An empty tree is None.

    Return the depth of the tree: start at the root, walk down from parent to child until you reach a leaf (a node with no children), and count the nodes you pass, both ends included. The depth is the largest count over every leaf. An empty tree has depth 0.

    Trees in the examples are written in level order, the way build_tree reads them: the root, then each row from left to right, with None where a child is missing.

    Example 1
    Inputroot = [1, 2, 3, None, 4, None, None, 5]Output4

    1 has children 2 and 3, 2 has a right child 4, and 4 has a left child 5. The longest path is 1, 2, 4, 5: four nodes.

    Example 2
    Inputroot = [7]Output1

    One node is a path of one node.

    Example 3
    Inputroot = []Output0

    An empty tree has no nodes.

    Constraints
    • 0 ≤ number of nodes ≤ 104

    • -100 ≤ node values ≤ 100

    • The tree is at most 500 levels deep, so a recursive solution fits under plain Python's default of about 1,000 nested calls.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The answer has the same shape as count_nodes: return 0 for None, and combine with 1 + max(left, right) instead of 1 + left + right. A good base case removes special cases: with 0 for an empty tree, a leaf comes out as 1 + max(0, 0) = 1, and a node with one child counts its empty side as 0, with no extra if.

    Changing a tree, and comparing two

    The work at a node can also change the node, or compare it with the node in the same position in another tree. The recursion stays the same.

    Mirroring a tree means that at every node, the left and right children trade places. The first swap that comes to mind, two separate assignments, loses a child. Predict it.

    PredictTwo assignments for a swap

    This code tries to swap the root's two children with two separate assignments. Type exactly what it prints.

    root = build_tree([1, 2, 3])
    root.left = root.right
    root.right = root.left
    print(root.left.val, root.right.val)
    

    Python's tuple assignment reads the whole right side before it changes anything, so root.left, root.right = root.right, root.left swaps correctly. The trace swaps the children of the root of build_tree([1, 2, 3, 4]). Watch the 4.

    Step throughOne swap moves two whole subtrees
    Step 1 of 4
    Line 1 is about to run.
    root = build_tree([1, 2, 3, 4])
    root.left, root.right = root.right, root.left
    print(tree_values(root))
    Names
    no names yet
    Output
    (nothing printed yet)

    Now mirror the whole tree: what does an empty tree become, and what does a node do besides trusting the calls on its children?

    easyTrees, depth-firstRecursion target 15 min

    Invert a binary tree

    You get the root of a binary tree. Turn the tree into its mirror image: at every node, the left child and the right child trade places, all the way down. Change the nodes you were given and return the same root. An empty tree (None) stays empty: return None.

    Trees in the examples are written in level order, the way build_tree reads them: the root, then each row from left to right, with None where a child is missing.

    Example 1
    Inputroot = [1, 2, 3, 4, 5, 6, 7]Output[1, 3, 2, 7, 6, 5, 4]

    Every node's children swap. In a full tree like this one (every row filled), each row ends up reading backwards.

    Example 2
    Inputroot = [1, 2, None, 3]Output[1, None, 2, None, 3]

    A chain that leans left becomes a chain that leans right.

    Example 3
    Inputroot = []Output[]

    An empty tree is its own mirror: return None.

    Constraints
    • 0 ≤ number of nodes ≤ 100

    • -100 ≤ node values ≤ 100

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Each swap touches only one node's two pointers, so a node may swap before or after the calls on its children, as long as it swaps once. Swapping between the two calls breaks it: the second call goes into the subtree that was already mirrored and undoes it, and the other subtree is never mirrored.

    Same tree walks two trees at once. One call compares the two nodes in the same position, then asks the same question of the two left children and of the two right children. Check the empty cases before reading .val: two Nones match, exactly one None is a mismatch, and None has no .val.

    easyTrees, depth-firstRecursion target 15 min

    Same tree

    You get the roots p and q of two binary trees. Return True if they are the same tree and False if not. Two trees are the same when they have the same shape and every pair of nodes in matching positions holds equal values. Two empty trees (None and None) are the same.

    Trees in the examples are written in level order, the way build_tree reads them: the root, then each row from left to right, with None where a child is missing.

    Example 1
    Inputp = [5, 3, 8, 1], q = [5, 3, 8, 1]OutputTrue

    Same shape, same value in every position.

    Example 2
    Inputp = [5, 3], q = [5, None, 3]OutputFalse

    Same values, different shape: 3 is a left child in p and a right child in q.

    Example 3
    Inputp = [5, 3, 8], q = [5, 8, 3]OutputFalse

    Same shape, but the two children hold different values.

    Constraints
    • 0 ≤ number of nodes in each tree ≤ 100

    • -104 ≤ node values ≤ 104

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    and stops at the first False, so the walk ends at the first difference. All three problems share one skeleton: a base case for None, the work at one node, and calls on the children that you trust.

    Last, practice that follow-up out loud. The words you write here are the words you will say in the room.

    Say itSay it like you would in the room

    The interviewer says: "Your recursive max_depth works. Now the tree can be a chain 100,000 nodes deep." Say what breaks and how you would change the code, with its cost, in a few plain sentences.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Passing answers up the tree