Python 3D Academyবাংলা

Breadth-first: level order with a queue

🌍 In real life. Good news reaches a big family one generation at a time. Gran tells her children; each of them tells their own children; then the grandchildren tell theirs. Nobody in the youngest generation hears it before everyone in the generation above. Or picture a school's staff chart read row by row: the head teacher, then the deputies, then every class teacher.

Reading a tree level by level, top row first and each row from left to right, is level order, and the tool that makes it easy is the queue from Chapter 40.

The idea in one sentence: a breadth-first traversal keeps the nodes waiting to be visited in a queue: it takes the node at the front, visits it, and puts that node's children at the back, so every level is visited before the level below it.

Its words:

  • breadth-first search (BFS): visiting everything near the start before anything further away; in a tree, level by level
  • level order: the order BFS visits a tree's nodes
  • queue: first in, first out; Python's collections.deque adds at the back with append and takes from the front with popleft, both in O(1)
  • frontier: the nodes waiting in the queue

How it works, step by step:

  1. put the root in the queue
  2. while the queue is not empty, take the node at its front (popleft) and visit it
  3. put its children at the back, left child first, skipping missing ones
  4. when the queue is empty, every node has been visited

Watch the queue on the left: the front node leaves for the order row, and its children glide into the back of the queue:

Why it is correct. A node's children join the queue only when the node itself leaves it. So the children of the root (depth 1) join before any node of depth 2 can, the nodes of depth 2 join while depth 1 is leaving, and so on. Because a queue lets things out in the order they came in, all of one level leaves before any of the next. Each node joins once, when its one parent is visited, so each is visited exactly once. To get the levels as separate lists, notice that when a level starts, the queue holds exactly that level: take len(queue) nodes and you have the whole row.

What it costs, by counting. Every node joins the queue once and leaves once, and each move is O(1) with a deque, so the time is O(n). The memory is the queue: at most about one level plus the start of the next. In a full tree the bottom level holds about half of all the nodes, so the queue can hold about n/2: O(n), where a depth-first walk needs only O(h). With a plain list, pop(0) moves every item still waiting each time, and in a full tree up to about half the nodes wait at once, so the pops add up to about n²/4 moves: about 2,500,000,000 for 100,000 nodes. That is O(n²), against O(n) with a deque.

from collections import deque
class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def level_order(root):
    if root is None:
        return []
    levels, queue = [], deque([root])
    while queue:
        row = []
        for _ in range(len(queue)):    # exactly the nodes of this level
            node = queue.popleft()
            row.append(node.val)
            for child in (node.left, node.right):
                if child is not None:
                    queue.append(child)
        levels.append(row)
    return levels

root = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(level_order(root))
print(level_order(None))

# the same queue gives the nearest leaf: the first leaf to leave it
def min_depth(root):
    if root is None:
        return 0
    queue = deque([(root, 1)])
    while queue:
        node, level = queue.popleft()
        if node.left is None and node.right is None:
            return level               # the first leaf out of the queue is the nearest
        for child in (node.left, node.right):
            if child is not None:
                queue.append((child, level + 1))

print(min_depth(root))
print(min_depth(Node(1, Node(2, Node(4)), Node(3))))

Mistakes and edge cases.

  • list.pop(0) as the queue: it works, but each pop moves the whole list; use deque.popleft()
  • pop() from the back: that turns the queue into a stack, and the walk becomes depth-first (root, then the right side first)
  • mixing levels: if you loop while queue without taking exactly len(queue) nodes first, children of this level end up in the same row
  • an empty tree: deque([None]) would give None.val, AttributeError; return [] for root is None first
  • missing children: check child is not None before adding it, or skip None when it comes out of the queue

Quiz

  1. What does this print?

    from collections import deque
    class Node:
        def __init__(self, val, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    
    def bfs(root):
        order, queue = [], deque([root])
        while queue:
            node = queue.popleft()
            if node is None:
                continue
            order.append(node.val)
            queue.append(node.left)
            queue.append(node.right)
        return order
    
    print(bfs(Node(1, Node(2, None, Node(4)), Node(3))))
  2. Here the queue is used from the wrong end: pop() takes from the back. What does it print?

    class Node:
        def __init__(self, val, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    
    def walk(root):
        order, waiting = [], [root]
        while waiting:
            node = waiting.pop()
            order.append(node.val)
            for child in (node.left, node.right):
                if child is not None:
                    waiting.append(child)
        return order
    
    print(walk(Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))))
  3. Why use collections.deque for the queue instead of a list with pop(0)?

    • popleft() is O(1), but list.pop(0) moves every other item: O(n) each time
    • A list can't hold tree nodes
    • deque visits the nodes in a different order
  4. A full binary tree has 7 levels (127 nodes). What is the most the level-order queue holds at once?

    • 64: the whole bottom level
    • 7: one per level
    • 127: every node
  5. level_order(None) crashes with AttributeError: 'NoneType' object has no attribute 'val'. On which line does it crash?

    def level_order(root):
        levels, queue = [], deque([root])
        while queue:
            row = []
            for _ in range(len(queue)):
                node = queue.popleft()
                row.append(node.val)
                for child in (node.left, node.right):
                    if child is not None:
                        queue.append(child)
            levels.append(row)
        return levels

Coding tasks

  1. Write level_order(root): the values level by level, as a list with one list per level, each from left to right ([] for an empty tree). deque is already imported.

  2. A family raises money for a school trip, and the tree holds what each person gave. Write level_sums(root): the total of each generation (each level), from the top down ([] for an empty tree).

  3. Write min_depth(root): how many levels down the nearest leaf is (the root alone is 1, an empty tree is 0). The starter is wrong for nodes with only one child: a missing child is not a leaf. Fix it, for example with a level-order walk that stops at the first leaf.