Sub topic 6
Preorder: node, left, right
This chapter assumes you can read recursive Python and know how the call stack works. It also assumes you have the Node class from the earlier chapter on representing binary trees.
The rule
Preorder is a depth-first traversal. At each node it does three things in this order:
- Visit the current node.
- Traverse the left subtree.
- Traverse the right subtree.
The current node comes first, which is why the order is called "pre".
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def preorder(node):
if node is None:
return []
return [node.value] + preorder(node.left) + preorder(node.right)
# 1
# / \
# 2 3
# / \
# 4 5
root = Node(1, Node(2, Node(4), Node(5)), Node(3))
print(preorder(root)) # [1, 2, 4, 5, 3]The None check is the base case. An empty subtree contributes an empty list, so the recursion stops at the leaves' missing children.
Tracing the call order
Walk through the tree by hand to see why the output is [1, 2, 4, 5, 3].
- Visit 1, then go left to 2.
- Visit 2, then go left to 4.
- Visit 4. Both of its children are empty, so return to 2.
- Go right from 2 to 5 and visit it. Return to 1.
- Go right from 1 to 3 and visit it.
Where preorder is useful
A parent always appears before every node in its subtrees. The first value in the output is the root. This makes preorder a good fit for:
- Copying a tree, because you must create a parent before you attach children to it.
- Serializing a tree, because the root is written first and a reader can rebuild from the top down.
- Printing a directory listing, where a folder appears before its contents.
Avoiding quadratic cost with a helper
The version above builds a new list at every call. Each + copies its operands. On a tree shaped like a linked list, the copying adds up to O(n²) total work. An accumulator list avoids this:
def preorder_fast(node, out=None):
if out is None:
out = []
if node is not None:
out.append(node.value)
preorder_fast(node.left, out)
preorder_fast(node.right, out)
return outThis version appends once per node, so the time is O(n). The extra space is the recursion depth, which equals the tree height.
Common errors
- Missing base case. Without the
Nonecheck, the code fails withAttributeError: 'NoneType' object has no attribute 'value'. - Swapped order. Putting
[node.value]between the two recursive calls gives inorder. Putting it last gives postorder. - Ignoring return values. In the accumulator version, the recursive calls mutate
out. In the concatenating version, dropping the return value of a recursive call loses that subtree's values.
Exercise
What is the preorder output for the tree whose root is 10, with left child 20 (which has a right child 40) and right child 30?
Show answer
[10, 20, 40, 30]. Visit 10, go left to 20 and visit it, 20 has no left child so go right to 40 and visit it, then return to 10 and visit 30.