Sub topic 14
Why Inorder on a BST Gives Sorted Output
This chapter assumes you know the binary search tree (BST) property, the recursive inorder traversal, and the Node class from earlier chapters. Keys are distinct.
The argument
Inorder visits the left subtree, then the node, then the right subtree. The BST property says that every key in the left subtree is smaller than the node, and every key in the right subtree is larger. Together, these two facts give the sorted order.
You can prove this by induction on the number of nodes:
- An empty tree produces an empty list, and a single node produces a one-item list. Both are sorted.
- Take a tree with root
r. By the induction hypothesis,inorder(left)is sorted, and so isinorder(right). - Every item in
inorder(left)is smaller thanr, and every item ininorder(right)is larger. - So
inorder(left) + [r] + inorder(right)is sorted.
Inorder on this tree gives 1, 3, 4, 5, 8, 9. Each key's subtree is read in full before the next ancestor is visited.
Using the property as a check
The reverse also holds. A tree is a valid BST exactly when its inorder output is strictly increasing. This gives a simple validator.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def inorder(node):
if node is None:
return []
return inorder(node.left) + [node.value] + inorder(node.right)
def is_bst(root):
keys = inorder(root)
return all(a < b for a, b in zip(keys, keys[1:]))
good = Node(5, Node(3, Node(1), Node(4)), Node(8, None, Node(9)))
bad = Node(5, Node(3, None, Node(7)), Node(8))
print(inorder(good), is_bst(good)) # [1, 3, 4, 5, 8, 9] True
print(inorder(bad), is_bst(bad)) # [3, 7, 5, 8] FalseWhat you get from it
- Listing all keys in order costs O(n), with no sorting step.
- Stopping an inorder traversal after k visits gives the k-th smallest key.
- Inserting n keys into a BST and then reading it inorder is a sort. It takes O(n log n) time on average. If the input is already sorted, the tree degenerates into a chain and the cost rises to O(n²).
Exercise
Inorder on a tree returns [2, 4, 3, 6, 7]. Can the tree be a BST? Explain.
Show answer
No. A BST's inorder output must be strictly increasing, and 4 is followed by 3, which is smaller. So the tree violates the BST property somewhere.