Sub topic 11
Inorder Traversal Yields Sorted Keys
Assume you know recursion, object references, and the binary search tree (BST) property. A BST stores every key smaller than a node in its left subtree and every key larger than the node in its right subtree. This chapter explains why inorder traversal of such a tree produces keys in sorted order.
The inorder rule
Inorder traversal follows this order:
- Visit the left subtree.
- Visit the current node.
- Visit the right subtree.
For a BST, the left subtree contains smaller keys, so it must be processed first. The current key is next. The right subtree contains larger keys, so it is processed last.
Consider this tree:
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13Its inorder traversal is:
1, 3, 4, 6, 7, 8, 10, 13, 14The result is ascending because the same rule applies recursively inside every subtree.
Implementation
The traversal itself does not explicitly sort values. It relies on the ordering already maintained by the BST.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def inorder(node, out):
if node is None:
return
inorder(node.left, out)
out.append(node.key)
inorder(node.right, out)
root = Node(8)
root.left = Node(3)
root.right = Node(10)
root.left.left = Node(1)
root.left.right = Node(6)
root.left.right.left = Node(4)
root.left.right.right = Node(7)
values = []
inorder(root, values)
print(values)The output is:
[1, 3, 4, 6, 7, 8, 10]With n nodes, inorder traversal takes O(n) time because it visits every node once. Its recursive call stack uses O(h) additional space, where h is the tree height. A balanced tree has h = O(log n), while a skewed tree can have h = O(n).
Why the result is sorted
A useful proof uses induction on the subtree size.
- An empty tree or one-node tree is already sorted.
- Assume inorder traversal sorts the left and right subtrees.
- Every key in the left result is smaller than the current key.
- Every key in the right result is larger than the current key.
- Concatenating left result, current key, and right result is therefore sorted.
This proof depends on the BST property. Inorder traversal of an arbitrary binary tree does not usually produce sorted output.
Common errors
- Using preorder or postorder instead of inorder. Those visits place the root before or after both subtrees.
- Forgetting that the BST invariant must hold at every subtree, not only at the root.
- Assuming duplicates have one universal position. If duplicates are allowed, the implementation must choose a rule, such as “equal keys go left” or “equal keys go right,” and use it consistently.
- Calling the result sorted when keys are sorted in descending order. Reversing the traversal order, right subtree, node, left subtree, produces descending order.
Exercise
A BST contains the keys 5, 2, 8, 1, 3, and 7. What does inorder traversal return, and what is its time complexity?
Show answer
It returns [1, 2, 3, 5, 7, 8]. The traversal takes O(n) time because it visits all n nodes.