ENع
←Tree traversals
Lesson 14 · Search trees

Tree traversals: pre-order, in-order, post-order and level order

14 min9 steps5 questionsIntermediate
About this lesson

A traversal visits every node of a tree exactly once. Walk a 7-key binary search tree and see that pre-order, in-order and post-order are one recursive walk that passes each node three times; only the pass that prints changes. Then switch to a queue for level order. The Software lesson "Trees" covers search, insert and a tree that turns into a line, and "Comparing growth rates: O, Omega and Theta" defines the Θ used for the cost.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 14 · Interactive
01 / 09

One tree, four orders

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.

        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)))
Loading figure…
or ← →
Read the lesson step by step
  1. One tree, four orders

    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.

            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)))
  2. One walk, three passes

    Recursion walks the tree the same way every time: go left, come back, go right, come back. Follow the dot round the outside. It passes each node three times: on the way down, between its children, and on the way back up.

    the walk round the tree
    pass 1  arriving, before the left child
    pass 2  between left and right child
    pass 3  leaving, after the right child
    
    7 nodes × 3 passes = 21 passes
  3. The code: three slots

    In Python the walk is a function that calls itself on the left child, then on the right. The print can sit in one of three slots: before both calls, between them, or after both. Each slot matches one pass.

    1  def dfs(n, slot):
    2      if n is None: return
    3      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)
    
    slot 1 (line 3): pre-order
    slot 2 (line 5): in-order
    slot 3 (line 7): post-order
  4. Pre-order: node first

    Pre-order prints a node on the first pass, before its children, so the root comes first: 40 20 10 30 60 50 70. Every parent is printed before its children, which is the order you need to copy a tree.

    dfs(root, 1)
    node, then left subtree, then right subtree
    
    printed: 40 20 10 30 60 50 70
    parents before children
  5. In-order: sorted keys

    In-order prints on the second pass: after the whole left subtree, before the right one. In a binary search tree everything left is smaller, so the keys come out sorted: 10 20 30 40 50 60 70.

    dfs(root, 2)
    left subtree, then node, then right subtree
    
    printed: 10 20 30 40 50 60 70
    a BST in-order is always sorted
  6. Post-order: children first

    Post-order waits for the third pass, when both children are done: 10 30 20 50 70 60 40. The root comes last. Use it when a node needs its children finished first, like deleting a tree or adding up folder sizes.

    dfs(root, 3)
    left subtree, then right subtree, then node
    
    printed: 10 30 20 50 70 60 40
    children before parents
  7. All three cost Θ(n)

    All three orders are the same walk, so they cost the same. dfs runs once per node, plus once per empty child, which returns at once. 7 nodes have 8 empty children: 15 calls, 2n + 1. That is Θ(n) time.

    calls on a node         7
    calls on an empty child 8
    total                   15
    
    any binary tree with n nodes has n + 1 empty children,
    so dfs runs 2n + 1 times: Θ(n)
  8. Level order needs a queue

    Level order reads the tree row by row, top to bottom, left to right. The walk cannot do that: it dives down first. A queue can. It is a line: add at the back, take from the front. Start with the root in it.

    1  def 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)
    
    queue: [40]
    deque: O(1) append and popleft
  9. Level order: row by row

    Repeat: take the front node, print it, add its children at the back. Children wait behind everything already in line, so each row prints before the next: 40 20 60 10 30 50 70.

    take 40, printqueue []
      add 20      queue [20]
      add 60      queue [20, 60]
    take 20, printqueue [60]
      add 10      queue [60, 10]
      add 30      queue [60, 10, 30]
    take 60, printqueue [10, 30]
      add 50      queue [10, 30, 50]
      add 70      queue [10, 30, 50, 70]
    take 10, printqueue [30, 50, 70]
    take 30, printqueue [50, 70]
    take 50, printqueue [70]
    take 70, printqueue []
    
    printed: 40 20 60 10 30 50 70

Quiz Unlocks after the last step.