Sub topic 6
Traversals and why in-order gives sorted keys
This chapter assumes you can write recursive functions in Python, know the binary search tree (BST) ordering property (left subtree keys are smaller, right subtree keys are larger), and have the Node class and insert function from the earlier chapters.
What a traversal is
A traversal visits every node in a tree exactly once. A tree has no single "next" pointer like a linked list, so you must choose an order. The three standard depth-first orders differ only in when you handle the current node relative to its two subtrees.
| Order | Sequence | Typical use |
|---|---|---|
| Pre-order | node, left, right | Copying a tree, serializing it |
| In-order | left, node, right | Reading keys in sorted order |
| Post-order | left, right, node | Deleting a tree, evaluating children first |
The three orders in code
Each traversal is a short recursive generator. The base case is an empty subtree (None).
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def preorder(node):
if node is not None:
yield node.key
yield from preorder(node.left)
yield from preorder(node.right)
def inorder(node):
if node is not None:
yield from inorder(node.left)
yield node.key
yield from inorder(node.right)
def postorder(node):
if node is not None:
yield from postorder(node.left)
yield from postorder(node.right)
yield node.key
root = None
for k in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, k)
print(list(preorder(root))) # [50, 30, 20, 40, 70, 60, 80]
print(list(inorder(root))) # [20, 30, 40, 50, 70, 60, 80][::1]
print(list(postorder(root))) # [20, 40, 30, 60, 80, 70, 50]Note that the in-order output is [20, 30, 40, 50, 60, 70, 80]. The three orders produce different sequences from the same tree, and only in-order is sorted.
Why in-order is sorted
The proof follows from the ordering property and induction on the tree.
- For any node, every key in its left subtree is smaller than the node's key.
- Every key in its right subtree is larger.
- In-order visits the whole left subtree first, then the node, then the whole right subtree.
- By induction, each subtree's in-order output is already sorted. So the full output is: sorted smaller keys, then the node's key, then sorted larger keys. That whole sequence is sorted.
An empty tree is trivially sorted, which gives the base case.
Reading the tree left to right along the bottom edge and up through the parents gives 20, 30, 40, 50, 60, 70, 80.
Cost of a traversal
Every node is visited once, so a traversal takes O(n) time for n keys. Unlike search, this does not depend on the height. The recursion uses O(h) stack space, where h is the tree's height. On a degenerate chain of 100,000 nodes, Python's default recursion limit (about 1,000) raises RecursionError.
Common errors
- Using pre-order or post-order and expecting sorted output. Only in-order is sorted.
- Forgetting
yield from. Callinginorder(node.left)withoutyield fromcreates a generator that is never consumed, so the left subtree is silently skipped. - Collecting results in a global list. A generator or an explicit accumulator argument keeps the function reusable.
- Assuming the traversal checks validity. If the tree breaks the ordering property, in-order output will not be sorted. You can use this as a validity check: a tree is a valid BST if its in-order keys are strictly increasing.
Exercise
A BST is built by inserting 8, 3, 10, 1, 6 in that order. Write the post-order sequence and explain why the in-order sequence is 1, 3, 6, 8, 10.
Show answer
The tree has root 8, left child 3 (with children 1 and 6), and right child 10. Post-order visits left, right, then node: 1, 6, 3, 10, 8. In-order is sorted because every key in a node's left subtree is smaller and every key in its right subtree is larger, so visiting left, node, right yields ascending keys at every level.