Sub topic 5
Preorder, Inorder, Postorder, and Level Order
Assume you know basic recursion, queues, object references, and Big-O notation. A tree traversal is a systematic way to visit every node exactly once. The traversal name describes when the algorithm visits a node relative to its left and right subtrees.
Consider this binary tree:
The three depth-first traversals
Depth-first traversal follows one branch as far as possible before visiting other branches. For a node N with left subtree L and right subtree R, the orders are:
- Preorder:
N, L, R - Inorder:
L, N, R - Postorder:
L, R, N
For the example tree:
| Traversal | Visit order |
|---|---|
| Preorder | A, B, D, E, C, F |
| Inorder | D, B, E, A, C, F |
| Postorder | D, E, B, F, C, A |
A recursive implementation makes the timing rule visible:
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def preorder(node, out):
if node:
out.append(node.key)
preorder(node.left, out)
preorder(node.right, out)
def inorder(node, out):
if node:
inorder(node.left, out)
out.append(node.key)
inorder(node.right, out)
def postorder(node, out):
if node:
postorder(node.left, out)
postorder(node.right, out)
out.append(node.key)
root = Node("A")
root.left = Node("B")
root.right = Node("C")
root.left.left = Node("D")
root.left.right = Node("E")
root.right.right = Node("F")
for traversal in (preorder, inorder, postorder):
result = []
traversal(root, result)
print(result)The three functions have the same structure. Only the position of out.append(node.key) changes. Each traversal takes O(n) time for n nodes because every node is processed once. Recursive depth is O(h), where h is the tree height.
Level-order traversal
Level order is a breadth-first traversal. It visits the root, then all nodes at depth 1, then all nodes at depth 2, and so on. It uses a queue, which is a first-in, first-out data structure.
from collections import deque
def level_order(root):
out = []
queue = deque([root] if root else [])
while queue:
node = queue.popleft()
out.append(node.key)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return outFor the example, level order produces A, B, C, D, E, F. Its time cost is O(n). The queue can hold O(w) nodes, where w is the maximum width of the tree. In a complete tree, that width can be close to n / 2.
In a binary search tree, inorder traversal is especially useful: it produces the keys in sorted order. The other traversal orders do not generally have this property.
Exercise
A binary tree has root 8, left child 3, right child 10, and node 3 has children 1 and 6. What are its preorder, inorder, postorder, and level-order traversals?
Show answer
Preorder: 8, 3, 1, 6, 10. Inorder: 1, 3, 6, 8, 10. Postorder: 1, 6, 3, 10, 8. Level order: 8, 3, 10, 1, 6.