Edexcel International Advanced Level Computer Science, point 18.2.8
Traversing a tree means visiting every node once (14.1.4). The three depth-first orders are naturally recursive, because each subtree is itself a tree. In Unit 4 you must be able to select, amend and write them. Check the PLS for details.
The tree used in the examples
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# 8
# / \
# 3 10
# / \ \
# 1 6 14
root = Node(8,
Node(3, Node(1), Node(6)),
Node(10, None, Node(14)))
The idea
For any node:
- Base case: if the node is
None(no node), do nothing and return. - Recursive case: handle the node's value, and traverse the left and right subtrees by calling the same function.
What differs is when the node's own value is handled, before, between or after the two subtree calls.
a. Pre-order traversal: node, left, right
def pre_order(node, result=None):
if result is None:
result = []
if node is not None:
result.append(node.value) # the node FIRST
pre_order(node.left, result)
pre_order(node.right, result)
return result
print(pre_order(root)) # [8, 3, 1, 6, 10, 14]
Uses: copying a tree (parents before children), prefix expressions, saving a tree's structure.
b. In-order traversal: left, node, right
def in_order(node, result=None):
if result is None:
result = []
if node is not None:
in_order(node.left, result)
result.append(node.value) # the node IN THE MIDDLE
in_order(node.right, result)
return result
print(in_order(root)) # [1, 3, 6, 8, 10, 14]
On a binary search tree, in-order gives the values in sorted order.
c. Post-order traversal: left, right, node
def post_order(node, result=None):
if result is None:
result = []
if node is not None:
post_order(node.left, result)
post_order(node.right, result)
result.append(node.value) # the node LAST
return result
print(post_order(root)) # [1, 6, 3, 14, 10, 8]
Uses: deleting a tree (children before parents), postfix (reverse Polish) expressions, evaluating expression trees.
Summary
| Order | Rule | Result for the tree |
|---|---|---|
| Pre-order | Node, left, right | 8, 3, 1, 6, 10, 14 |
| In-order | Left, node, right | 1, 3, 6, 8, 10, 14 |
| Post-order | Left, right, node | 1, 6, 3, 14, 10, 8 |
Only the position of the line that handles the node differs. The three functions are otherwise identical.
Tracing a recursive traversal
in_order(root): the calls go down the left side first, record a value on the way back up, then go right.
in_order(8)
in_order(3)
in_order(1)
in_order(None) -> nothing (left of 1)
record 1
in_order(None) -> nothing (right of 1)
record 3
in_order(6)
in_order(None), record 6, in_order(None)
record 8
in_order(10)
in_order(None) -> nothing
record 10
in_order(14)
in_order(None), record 14, in_order(None)
Recorded in this order: 1, 3, 6, 8, 10, 14.
Memory: each call uses a stack frame, so the depth of the stack is the height of the tree: about for a balanced tree, but for a lopsided one (which could cause a RecursionError for a very large unbalanced tree).
Without recursion
An iterative version needs an explicit stack (4.3.1), for example in-order:
def in_order_iterative(root):
result, stack, current = [], [], root
while current is not None or stack:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.value)
current = current.right
return result
print(in_order_iterative(root)) # [1, 3, 6, 8, 10, 14]
The recursive version is shorter and clearer; the iterative version avoids deep recursion.
Worked example
Task: an expression tree represents (3 + 4) × 2: the root is *, its left child is a + node (with children 3 and 4) and its right child is 2. Find the post-order traversal, and say what it represents.
expr = Node("*", Node("+", Node(3), Node(4)), Node(2))
print(post_order(expr)) # [3, 4, '+', 2, '*']
print(pre_order(expr)) # ['*', '+', 3, 4, 2]
print(in_order(expr)) # [3, '+', 4, '*', 2]
- Post-order
3 4 + 2 *is reverse Polish (postfix) notation, which a stack can evaluate: push 3, push 4,+gives 7, push 2,*gives 14. - Pre-order
* + 3 4 2is prefix notation. - In-order
3 + 4 * 2is the ordinary written form (but without the brackets, so it would be read as 3 + 8 = 11, not 14).
This is why post-order is used to evaluate expression trees.
Exam tip: always write the base case (if node is not None). Learn the three rules by where the node is handled (pre: first, in: middle, post: last). When tracing, go left as far as you can, then back up, and apply the rule at each node. Check that in-order on a BST is sorted.
Check yourself
What is the base case of a recursive tree traversal?
When the node is None (an empty subtree), the function does nothing and returns.
What is the only difference between the pre-order, in-order and post-order functions?
Where the node's own value is handled: before, between or after the two recursive calls on the subtrees.
Give the in-order traversal of a tree with root 5, left child 2 and right child 9
2, 5, 9.
Which traversal gives postfix notation for an expression tree?
Post-order.
How deep does the call stack go in a recursive traversal?
As deep as the height of the tree.