402060307010501def dfs(n, slot):2 if n is None: return3 if slot == 1: print(n.key)4 dfs(n.left, slot)5 if slot == 2: print(n.key)6 dfs(n.right, slot)7 if slot == 3: print(n.key)1def bfs(root):2 q = deque([root])3 while q:4 n = q.popleft()5 print(n.key)6 for c in (n.left, n.right):7 if c: q.append(c)1234567frontbackcalls
Key blocks: the tree; small pads: pass 1 (left), 2 (front), 3 (right)Cells: what is printed, the queue, the call countThe rose dot: the walk; flying chips: keys being printed or queuedA binary search tree of 7 keys; the rose dot is the path recursion takes round it, passing each node three times. Printing on the first, second or third pass gives pre-order, in-order (sorted, in a BST) or post-order. Level order instead takes nodes from the front of a queue and adds their children at the back.

One walk round the tree

  1. This binary search tree holds 7 keys: smaller keys sit to the left, bigger to the right. A traversal visits every node exactly once. The question is in what order. Four standard orders give four different lists from the same tree.

Depth first

Breadth first

What happens

;; step 1/9 · tree
        40
      /    \
    20      60
   /  \    /  \
  10  30  50  70

n = 7 nodes, height 2
left subtree < node < right subtree

from collections import deque

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

root = Node(40, Node(20, Node(10), Node(30)),
                Node(60, Node(50), Node(70)))

The three passes are the times the recursion is at a node: when dfs(n) starts, when dfs(n.left) returns, and when dfs(n.right) returns. A real program prints in only one of the slots; the figure shows all three so you can compare them. Each call does O(1) work besides its two recursive calls, and a binary tree with n nodes has n + 1 empty child links, so dfs is called 2n + 1 times (15 here). CLRS Theorem 12.1 proves the same Θ(n) bound for the in-order walk.