Sub topic 11
Inorder traversal yields sorted keys
This chapter assumes you can read recursive Python and know the binary search tree (BST) property: every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger. You should also know the three depth-first traversals from the traversals chapter. Here we connect the two ideas and use the result to solve problems.
The claim
For a BST with distinct keys, the inorder traversal visits the keys in strictly increasing order.
Inorder means: traverse the left subtree, visit the node, traverse the right subtree. The BST property puts all smaller keys on the left and all larger keys on the right. Inorder reads exactly in that order.
Here the inorder of the left subtree is 20, 30, 40. Then the root 50 follows. Then the inorder of the right subtree, 60, 70, 80, follows.
Why it holds
The proof is a short induction on the number of nodes.
- Base case: an empty tree gives an empty sequence, and a single node gives one key. Both are trivially sorted.
- Inductive step: let the tree have root
r, left subtreeL, and right subtreeR. Both subtrees are smaller BSTs, so by the induction hypothesis their inorder sequences are sorted. - The inorder sequence of the whole tree is
inorder(L), thenr, theninorder(R). - By the BST property, every key in
Lis less thanr, and every key inRis greater thanr. - A sorted block of keys below
r, thenr, then a sorted block of keys abover, is sorted. ∎
The converse also holds. If a binary tree's inorder sequence is strictly increasing, the tree is a BST. A node's left subtree appears before it in the sequence, so its keys are smaller. The right subtree appears after it, so its keys are larger. This makes the inorder sequence an exact test for the BST property.
Seeing it run
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 inorder(node, out):
if node:
inorder(node.left, out)
out.append(node.key)
inorder(node.right, out)
root = None
for k in [50, 30, 70, 20, 40, 60, 80, 45, 10]:
root = insert(root, k)
result = []
inorder(root, result)
print(result)
assert result == sorted(result)The output is [10, 20, 30, 40, 45, 50, 60, 70, 80]. The insertion order was arbitrary, but the output is sorted. Every BST built from the same set of distinct keys has the same inorder sequence, whatever its shape.
Consequences you can use
Tree sort
To sort a list, insert every element into a BST, then run an inorder traversal.
- Insertion costs one root-to-leaf path per key. On random input the average cost is O(log n) per key, so O(n log n) in total.
- If the input is already sorted, each insertion extends a single chain, the tree degenerates into a linked list, and the total is O(n²).
- The inorder traversal always costs O(n), because each node is visited once.
Tree sort is therefore as good as the tree's height allows.
Validating a BST
A frequent bug is checking only each node against its direct children. That check accepts invalid trees.
Take root 10 with left child 5, and give 5 a right child 15. Locally, 5 < 10 and 15 > 5, so every parent-child pair looks fine. But 15 sits in the left subtree of 10 and is greater than 10. The inorder sequence is 5, 15, 10, which is not increasing, so the tree is rejected.
def is_bst(root):
prev = None
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if prev is not None and node.key <= prev:
return False
prev = node.key
node = node.right
return True
good = insert(insert(insert(None, 10), 5), 15)
bad = Node(10)
bad.left = Node(5)
bad.left.right = Node(15)
print(is_bst(good))
print(is_bst(bad))This prints True and then False. The function is an iterative inorder traversal that remembers only the previous key. It uses <= because a BST with distinct keys needs a strictly increasing sequence. It runs in O(n) time and O(h) extra space, where h is the height.
The k-th smallest key
Because inorder visits keys in rank order, the k-th node visited is the k-th smallest key. You can stop as soon as you reach it.
def kth_smallest(root, k):
stack = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
k -= 1
if k == 0:
return node.key
node = node.right
return None
print(kth_smallest(root, 3))For the tree built above, this prints 30. The cost is O(h + k): descend h levels to the minimum, then take k steps. The minimum is the first inorder node and the maximum is the last.
Successor and predecessor
The inorder successor of a key is the next key in the sorted sequence. If the node has a right subtree, the successor is the leftmost node of that subtree. Otherwise it is the nearest ancestor for which the node lies in the left subtree. The deletion chapter uses the first case when it replaces a node that has two children.
A GATE-style pattern: preorder to postorder
A common question gives the preorder of a BST and asks for its postorder. The inorder sequence is not given, but it is the sorted keys.
Suppose the preorder is 50, 30, 20, 40, 70, 60, 80.
- Sort the keys to get the inorder: 20, 30, 40, 50, 60, 70, 80.
- The first preorder key, 50, is the root. In the inorder it splits the keys into left (20, 30, 40) and right (60, 70, 80).
- Repeat on each side. In the left part the next preorder key is 30, which splits it into 20 and 40.
- In the right part the root is 70, with children 60 and 80.
- Postorder is left, right, root: 20, 40, 30, 60, 80, 70, 50.
This works because a BST always has the same inorder sequence for a given key set. Preorder plus inorder determines the tree, and the BST property supplies the inorder for free. This is why a single traversal is enough for a BST, while a general binary tree needs two.
A shortcut for preorder: the root is the first key. The left subtree is the maximal run of following keys smaller than the root. The right subtree is everything after that run.
What inorder does not tell you
- The shape. Many different BSTs share one inorder sequence. For keys 1, 2, 3 there are five trees, all with inorder 1, 2, 3. The count is a Catalan number, covered later in this tutorial. So an inorder sequence alone never identifies a BST.
- Duplicates. If equal keys are allowed, the inorder sequence is only non-decreasing. Also, whether equal keys go left or right depends on the insertion rule, so the tree must follow one consistent convention. The code in this tutorial ignores duplicates, so keys stay distinct.
- Other traversals. Preorder, postorder, and level order of a BST are generally not sorted. Do not assume a sorted preorder unless the tree is a chain going right.
Cost summary
| Task | Method | Time |
|---|---|---|
| List all keys in order | Inorder traversal | O(n) |
| Check the BST property | Inorder with previous key | O(n) |
| k-th smallest key | Inorder, stop early | O(h + k) |
| Tree sort, average case | n insertions plus inorder | O(n log n) |
| Tree sort, worst case | Degenerate chain | O(n²) |
Exercises
Exercise
The preorder traversal of a BST is 8, 3, 1, 6, 4, 7, 10, 14, 13. Write its inorder and postorder traversals.
Show answer
The inorder is the sorted keys: 1, 3, 4, 6, 7, 8, 10, 13, 14. The root is 8. The left subtree has preorder 3, 1, 6, 4, 7, with root 3, left child 1, and right subtree rooted at 6 with children 4 and 7. The right subtree has preorder 10, 14, 13, with root 10 and right child 14, which has left child 13. The postorder is 1, 4, 7, 6, 3, 13, 14, 10, 8.
Exercise
A binary tree has inorder traversal 2, 5, 9, 12, 20, but node 9 is the left child of a node holding 5. Is the tree a BST? Explain using the inorder test.
Show answer
The inorder sequence 2, 5, 9, 12, 20 is strictly increasing, so the converse of the claim says the tree is a BST. The situation described is inconsistent, though. If 9 were the left child of 5, then 9 would come before 5 in inorder and the sequence could not read 5, 9. So the stated tree cannot have that inorder sequence, and the description contains a mistake. The point is that the inorder sequence alone fixes the ordering of keys, so any structure claim must agree with it.
Exercise
Why is inserting n keys into an initially empty BST and then running an inorder traversal not guaranteed to sort in O(n log n) time?
Show answer
Each insertion costs time proportional to the current height, and the height depends on the insertion order. Sorted or reverse-sorted input builds a chain of height n − 1, so the insertions cost 1 + 2 + … + (n − 1), which is O(n²). The inorder traversal costs only O(n), so the insertions dominate.