Pre-order Traversal
A traversal visits every node of a tree exactly once. In a pre-order traversal you visit a node before its subtrees:
- Visit the node itself.
- Traverse the left subtree in pre-order.
- Traverse the right subtree in pre-order.
"Pre" refers to when the node is handled: before (pre) its children. This lesson and the next two use the same tree, built by inserting 40, 22, 61, 15, 30, 52, 70, 27 into a binary search tree:
40
/ \
22 61
/ \ / \
15 30 52 70
/
27The animation first builds the tree, then highlights the nodes in pre-order. Watch the list of visited values grow:
Recursive implementation
The definition translates directly into a recursive function. The base case is the empty subtree, where there is nothing to do.
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
root = Node(40,
Node(22, Node(15), Node(30, Node(27))),
Node(61, Node(52), Node(70)))
def preorder(node, out):
if node is None:
return
out.append(node.value) # 1. the node
preorder(node.left, out) # 2. the left subtree
preorder(node.right, out) # 3. the right subtree
order = []
preorder(root, order)
print(order)[40, 22, 15, 30, 27, 61, 52, 70]
The result matches the animation: the root comes first, and every node appears before all the nodes below it.
Watching the recursion
Printing with indentation shows how the calls nest. Each visit happens on the way down:
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
root = Node(40, Node(22, Node(15), Node(30, Node(27))), Node(61, Node(52), Node(70)))
def preorder(node, depth=0):
if node is None:
return
print(" " * depth + f"visit {node.value}")
preorder(node.left, depth + 1)
preorder(node.right, depth + 1)
preorder(root)visit 40
visit 22
visit 15
visit 30
visit 27
visit 61
visit 52
visit 70
This indented output is exactly how a file explorer shows a folder tree: each folder is printed before its contents. That is pre-order.
Iterative version with a stack
Recursion uses the call stack behind the scenes. You can use an explicit stack instead. Push the right child before the left one, so that the left one is popped (and visited) first:
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
root = Node(40, Node(22, Node(15), Node(30, Node(27))), Node(61, Node(52), Node(70)))
def preorder_iterative(root):
out, stack = [], [root]
while stack:
node = stack.pop()
out.append(node.value)
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
return out
print(preorder_iterative(root))[40, 22, 15, 30, 27, 61, 52, 70]
What is pre-order good for?
Copying or saving a tree. Writing nodes in pre-order (with markers for empty children) produces a description from which the exact tree can be rebuilt, because each parent is read before its children:
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
def serialize(node):
if node is None:
return ["#"]
return [str(node.value)] + serialize(node.left) + serialize(node.right)
def deserialize(tokens):
value = next(tokens)
if value == "#":
return None
return Node(int(value), deserialize(tokens), deserialize(tokens))
root = Node(40, Node(22, Node(15), Node(30, Node(27))), Node(61, Node(52), Node(70)))
text = " ".join(serialize(root))
print(text)
copy = deserialize(iter(text.split()))
print(" ".join(serialize(copy)) == text)40 22 15 # # 30 27 # # # 61 52 # # 70 # #
True
Prefix expressions. For an expression tree (operators inside, numbers at the leaves), pre-order gives prefix (Polish) notation, such as * + 3 4 2 for (3 + 4) * 2.
Complexity
Every node is visited once and does O(1) work, so a traversal takes O(n) time. The extra memory is the recursion depth (or stack size), which is the tree's height h: O(log n) for a balanced tree, O(n) for a degenerate one.
Test yourself
In pre-order traversal, when is a node visited?
- Before its left and right subtrees
- Between its left and right subtrees
- After both subtrees
- Level by level
What is the pre-order traversal of a root 1 with left child 2 and right child 3, where 2 has a left child 4?
- 1 2 4 3
- 4 2 1 3
- 4 2 3 1
- 1 2 3 4
In the iterative pre-order version, why is the right child pushed before the left?
- To save memory
- So the left child is popped and visited first
- Because right children are smaller
- It makes no difference