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

Lesson 4 of 5

Level by level

A queue hands out a tree's nodes one level at a time, top to bottom and left to right. Count the queue before you take a level's first node and you know where that level ends, which answers level order, the right side view and the nearest leaf.

About 1 hour 45 minutes, with the 2 problems worked in it
By the end you can
  • Trace a breadth-first walk of a tree with a deque and say what the queue holds after each step

  • Handle a tree one level at a time by taking len(queue) nodes per round

  • Return a tree's levels and its right side view

  • Find the minimum depth by stopping at the first leaf the walk reaches

  • Compare the queue's O(w) space with recursion's O(h) and say when each one wins

An interviewer draws a tree on the whiteboard. In code it is build_tree([4, 2, 7, 1, 3, 6]). As a reminder, each TreeNode has a value val and two children, left and right, and a missing child is None. build_tree reads its list row by row from the top, each row left to right, with None marking a missing child. Drawn out, this tree has three rows:

        4
      /   \
     2     7
    / \   /
   1   3 6

Then come the questions. What are the rows, from the top? [[4], [2, 7], [1, 3, 6]]. What do you see if you stand to the right of the tree? 4, 7 and 6: on each row, the rightmost node hides the others. Both are classic interview questions, and both are about whole rows.

The depth-first walks from earlier in this module do not go row by row. Preorder (a node, then its whole left subtree, then its whole right subtree) visits 4, 2, 1, 3, 7, 6. It reaches the bottom row on the left before it has seen 7, one row up. This lesson builds the walk that finishes one row before it starts the next, out of a tool from module 5: the queue.

A queue reads the rows

Which tool hands out nodes row by row? Recall the queue: a line where items join at the back and leave from the front, so the item that has waited longest always leaves first. Python's collections.deque (said "deck") is fast at both ends: queue.append(x) adds x at the back and queue.popleft() removes and returns the front item, each in O(1).

The walk: put the root in the queue. Then, until the queue is empty, take the front node, record it, and send its children to the back, left child first. if node.left: is true when the child exists, because a node counts as true and None counts as false. Before you step through, guess the order of the six values it prints.

Step throughA queue hands out the tree
Step 1 of 41
Line 1 is about to run.
from collections import deque
def walk_with_queue(root):
queue = deque([root])
while queue:
node = queue.popleft()
print(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
Names
no names yet
Output
(nothing printed yet)

Why do the rows come out in order? A node's children join behind every node already waiting. When 4 leaves, only its children, 2 and 7, are in line. The children of 2 and 7 join behind them, so the whole second row leaves before any of the third. And children of a node further left join earlier, so each row also leaves from left to right.

This walk is called breadth-first search, or BFS: it covers the full breadth of the tree, one row at a time, before it goes deeper. On a tree it is also called level order, because a row of the drawing is a level, the binary trees lesson's word for all the nodes the same number of steps below the root.

Notice that the output, 4, 2, 7, 1, 3, 6, is the list we gave build_tree. That list was level order all along: build_tree reads it with the same kind of queue, handing each waiting node the next two values as its children.

One word in that loop decides the walk. Change it and predict.

PredictOne word changed

This is the walk from the trace with one change: queue.pop() instead of queue.popleft(), so each node leaves from the back of the line. The tree is the same: 4 on top, 2 and 7 under it, 1 and 3 under 2, and 6 under 7. Type exactly what it prints, one value per line.

from collections import deque

def walk(root):
    queue = deque([root])
    while queue:
        node = queue.pop()
        print(node.val)
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

walk(build_tree([4, 2, 7, 1, 3, 6]))

Where one level ends

The printout 4, 2, 7, 1, 3, 6 has every node in the right order, but nothing marks where one level stops and the next begins. The interview question wants [[4], [2, 7], [1, 3, 6]]. How does the loop know that 7 ends a level?

Look back at the trace at the moments a level is about to start. When the second pass begins, the queue holds 2 and 7: exactly the second level. When the fourth pass begins, it holds 1, 3 and 6: exactly the third. Right before a level's first node leaves, the queue holds that whole level and nothing else.

The figure below runs the same walk on the same tree and stops at each of those moments, on steps titled "Level 1 starts", "Level 2 starts" and so on. It numbers the levels from 1 at the root. Press Next and watch the queue, listed front first under the tree.

So count before you take. The new loop works in rounds, one level per round. At the start of a round, size = len(queue) is the number of nodes on the level. Take exactly size nodes from the front. The children they send to the back wait for the next round. One round is one level. In code, the outer while loop runs once per round, and an inner for loop takes the size nodes.

Here is that loop answering a small question: the total of the values on each level. Before you step through, add up each row of the drawing yourself; the trace should return the same three numbers. Watch size at the start of each round.

Step throughOne round per level
Step 1 of 59
Line 1 is about to run.
from collections import deque
def level_totals(root):
if root is None:
return []
totals = []
queue = deque([root])
while queue:
size = len(queue)
total = 0
for _ in range(size):
node = queue.popleft()
total += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
totals.append(total)
return totals
Names
no names yet
Output
(nothing printed yet)

Three details in that code:

  • for _ in range(len(queue)) does the same as storing size first. range reads len(queue) once, when the loop starts, so the children added during the round do not stretch it. The last trace in this lesson uses that shorter form.
  • _ is the usual name for a loop variable the body does not use. In the trace it still takes the values 0, 1, and so on up to size - 1: the position of each node within its round.
  • The empty tree needs its own check. Without lines 4 and 5, deque([None]) would hand out None, and None.val raises an AttributeError.

Why does the promise hold? It is true at the start, with only the root waiting. During a round, every node of the level leaves and sends its children to the back. Every node on the next level is a child of some node on this level, so all of them join, and they join in left-to-right order because their parents leave in left-to-right order. When the round ends, the queue holds the next level and nothing else.

How big does w get? Try it on a full tree, one where every level has all the nodes it can hold.

Work it outHow wide does the queue get

build_tree([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) is a full tree: its four levels hold 1, 2, 4 and 8 nodes. Run level_totals from the trace on it. What is the largest number of nodes the queue holds at any moment? Type a whole number.

most nodes in the queue

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

Now build the loop yourself. This version counts the nodes on each level. The lines are here in the wrong order, plus two that do not belong.

Put in orderHow many on each level

Put the lines in order to build level_sizes(root), which returns how many nodes each level has, from the top. The tree has at least one node. The first line of the body sets up two names at once: sizes is [] and queue is deque([root]). for child in (node.left, node.right): visits the two children, left first, and if child: skips a missing one. Indentation is 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 child:
    • while queue:
    • while queue:
    • sizes, queue = [], deque([root])
    • node = queue.popleft()
    • for _ in range(len(queue)):
    • node = queue.pop()
    • def level_sizes(root):
    • queue.append(child)
    • return sizes
    • sizes.append(len(queue))
    • for child in (node.left, node.right):

    To recap: a queue walks a tree level by level, and counting the queue at the start of each round tells you exactly which nodes form the level. The round's notebook (a total, a count, a list) becomes one answer per level.

    The first problem collects each level's values in a list: the round loop with a fresh list where total was. It numbers the levels from 1 at the root, like the figure. Try it before you open the hints.

    mediumTree level by level (breadth-first)Queues and deques target 25 min

    Level order traversal

    A level of a binary tree is all the nodes the same number of steps below the root. The root is level 1, its children level 2, their children level 3.

    You get the root of a binary tree. Return its values level by level: a list with one inner list per level, starting with the root's level. Each inner list holds that level's values from left to right, as they appear in a drawing of the tree. An empty tree (root is None) gives [].

    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, None, 5, 6]Output[[1], [2, 3], [4, 5, 6]]

    Level 1 is the root. Level 2 is 2 and 3. Level 3 is 4, the left child of 2, then 5 and 6, the children of 3.

    Example 2
    Inputroot = [8, None, 5, 2]Output[[8], [5], [2]]

    8 has only a right child, 5, and 5 has only a left child, 2. Each level holds one node.

    Example 3
    Inputroot = []Output[]

    No nodes, so no levels.

    Constraints
    • 0 ≤ number of nodes ≤ 1.3 × 105

    • -104 ≤ node value ≤ 104

    • 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 solution is the round loop with level, a new list per round, in place of total. Its tests check two common slips: an empty tree must give [], not [[]], and a missing child must never join the queue, or a None would reach node.val.

    Seen from the right

    Back to the second whiteboard question: which node do you see on each level from the right?

    The tempting answer is to follow right pointers from the root: 4, then 7. But 7 has no right child, and the third level still has a node in view: 6, the left child of 7. Patching the walk to step left when there is no right child gets this tree right and still fails on others.

    Quick checkPatch the pointer walk

    A first try at the right side view walks one path down from the root, going right when there is a right child and left otherwise:

    def right_view_guess(root):
        view = []
        node = root
        while node:
            view.append(node.val)
            if node.right:
                node = node.right
            else:
                node = node.left
        return view

    On the lesson's tree it returns [4, 7, 6], which is right. What does it return for build_tree([1, 2, 3, 4])? There, 1 has children 2 and 3, and 4 is the left child of 2.

    Choose one answer, then check.

    What you see on each level is its last node from left to right, wherever it hangs. The round loop already hands out each level from left to right, so the last node of a round is the one in view. To know which node is last, give the loop variable a real name: in for i in range(size), i is the node's position within its round, so the node taken when i == size - 1 is the last one. Record that node. Every node still sends its children to the back, even the ones you do not record, because the rightmost node of the next level can be anyone's child.

    Before you write it, run the rounds by hand on a tree with two traps in it.

    On paperThe right side view by hand

    On paper, run the rounds on build_tree([1, 2, 3, 4, 5, 6, None, None, 7]). For each round, write the queue at the start of the round and circle its last node. Reveal one step at a time to check your work, then add up the values you circled.

    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.

    Sum of the values in the view

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

    Now write it.

    mediumTree level by level (breadth-first)Queues and deques target 25 min

    Right side view

    Stand to the right of a binary tree and look at it. On every level (all the nodes at the same distance from the root) you see exactly one node: the one furthest to the right. It hides the rest of its level.

    Your function gets the tree's root. Return the values you see, one per level, from the root's level down. An empty tree (root is None) gives [].

    The node you see is not always a right child. When the right side of the tree stops early, the lower levels are seen through nodes that hang on the left side.

    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 = [6, 2, 9, 1, 4, None, None, None, None, 3]Output[6, 9, 4, 3]

    The levels, left to right, are [6], [2, 9], [1, 4] and [3]. 9 has no children, so the two lowest levels are seen through 4 and 3, which hang under the 2.

    Example 2
    Inputroot = [5, 3, None, 8]Output[5, 3, 8]

    Below the root every node is a left child, and every node is alone on its level, so you see all of them.

    Example 3
    Inputroot = []Output[]

    No nodes, nothing to see.

    Constraints
    • 0 ≤ number of nodes ≤ 1.3 × 105

    • -104 ≤ node value ≤ 104

    • 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 left side view is the same loop recording i == 0. The largest value on each level is the same loop again, with a running maximum per round. When a question says "each level", reach for the rounds.

    Stop at the first leaf

    How far below the root is the nearest leaf? A leaf is a node with no children. The minimum depth of a tree is the number of nodes on the shortest path from the root down to a leaf, counted the way the max-depth problem counted the longest one. For the whiteboard tree it is 3: its leaves, 1, 3 and 6, are all on the third level.

    A depth-first walk cannot stop at the first leaf it meets. That leaf may be deep on the left while a shallower one waits on the right, on a branch the walk has not reached yet, so it has to keep going. A level-by-level walk meets the leaves in order of depth. The first leaf it takes is on the shallowest level that has one, so it can return right there. A counter, depth, goes up by one each round, so it always holds the number of the level being taken.

    The trace runs this on build_tree([1, 2, 3, 4, 5, None, None, 6, 7]). The left side goes four levels down, but 3, on the second level, has no children. Before you step through, guess how many nodes the walk takes from the queue before it returns.

    Step throughStop at the first leaf
    Step 1 of 30
    Line 1 is about to run.
    from collections import deque
    def min_depth(root):
    if root is None:
    return 0
    queue = deque([root])
    depth = 0
    while queue:
    depth += 1
    for _ in range(len(queue)):
    node = queue.popleft()
    if node.left is None and node.right is None:
    return depth
    if node.left:
    queue.append(node.left)
    if node.right:
    queue.append(node.right)
    Names
    no names yet
    Output
    (nothing printed yet)

    The function always returns from inside the loop. A tree with at least one node has at least one leaf, so the walk is sure to reach one.

    Now try a tree whose shallowest leaf is not the first node on its level.

    Work it outWhen does it stop

    Run min_depth from the trace on build_tree([1, 2, 3, 4, None, 5, 6, None, 7]). In this tree, 1 has children 2 and 3, 2 has only a left child, 4, 3 has children 5 and 6, and 4 has only a right child, 7. How many nodes does the walk take from the queue (how many times does popleft run) before it returns?

    nodes taken

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

    Now write it without looking back at the trace. The tests include the one-child trap.

    Code itWrite minimum depth

    Write min_depth(root), which returns the number of nodes on the shortest path from the root down to a leaf (a node with no children). An empty tree gives 0. Walk level by level and return as soon as you take a leaf. Then press Watch it run to see where the walk stops.

    ⌘+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.

    For more practice, the bank has Minimum depth (LeetCode 111, Minimum Depth of Binary Tree): the same walk on new trees, plus a chain 100,000 levels deep, which the loop handles and a recursive version cannot. Try it after this lesson.

    Queue or recursion

    Why a queue and not recursion? An interviewer may ask exactly that. Time is the same either way: O(n), one visit per node. The difference is space, and it depends on the shape of the tree.

    The queue holds at most the rest of one level plus part of the next, so it needs O(w) space, where w is the number of nodes on the widest level. A recursive walk keeps one open call for each node on the path from the root to where it is now, so it needs O(h) space, where h is the height, the number of levels. Two shapes pull them apart:

    TreeNodesQueue holds at mostOpen recursive calls, at most
    Full, 10 levels1,023512 (the last level)about 10
    A chain, each node the left child of the one above1,0001about 1,000

    Height also has a hard limit. Plain Python stops at about 1,000 nested calls by default with a RecursionError, and this lab allows 5,000. A queue is an ordinary loop, so a tree 100,000 levels deep is no problem for it.

    Quick checkWhich needs more memory

    A full tree has 10 levels and 1,023 nodes, and its last level holds 512 of them. You walk it two ways: level by level with a queue, and with a recursive depth-first function. Which one needs more extra memory at its peak?

    Choose one answer, then check.

    So pick by the question first. When the question is about levels (rows, a side view, the nearest leaf), the queue visits the nodes in the order the answer needs them. When each node's answer is built from its children's answers (height, balance, a diameter), recursion fits. And when the tree may be very deep, a loop avoids the limit.

    Here is that last point in practice. The max-depth problem counted levels with recursion, one open call per level. Count them with a queue instead, and a chain 100,000 nodes deep, which would stop the recursion, becomes harmless.

    Code itCount the levels with a queue

    Write count_levels(root), which returns how many levels the tree has. That is the max depth from the binary trees lesson, counted in rounds instead of with recursion. An empty tree has 0 levels. One test is a chain 100,000 nodes deep, far past the lab's recursion limit of 5,000 nested calls: recursion stops there with a RecursionError, and a loop does not. Then press Watch it run to see the rounds.

    ⌘+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.

    Last, say it out loud. The words you write here are the words you will use in the room.

    Say itWhy BFS over DFS?

    You solved minimum depth with a queue, and the interviewer asks: "Why BFS over DFS here?" Write what you would say. Cover the walk, the notebook, the promise and the cost, and why the queue suits this question better than recursion.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Binary search trees