Sub topic 1
Quick review: the binary search tree invariant
Prerequisites
This chapter assumes you already know the following:
- Binary search tree (BST) search, insertion and deletion at a basic level.
- Recursion and tree terms: root, leaf, subtree, height.
- Big-O notation, including the difference between O(log n) and O(n).
- Enough Python to read short classes and recursive functions.
If any of these are unfamiliar, review them first. This chapter only refreshes the one idea that every later chapter depends on.
The ordering invariant
A binary search tree is a binary tree where every node holds a key, and the keys obey one rule:
- Every key in a node's left subtree is smaller than the node's key.
- Every key in a node's right subtree is larger than the node's key.
This rule is the BST invariant. It applies to the whole subtree, not only to the immediate children. A node's left child may be smaller than the node, but if that child has a right child larger than the node, the tree is broken.
In the right-hand tree, 7 is a right child of 3, so it satisfies the local rule. It still sits in the left subtree of 5, and 7 is larger than 5. The invariant fails.
Why the invariant gives fast search
Searching uses the invariant to discard one whole subtree at each step. Compare the target with the current key. If the target is smaller, go left. If it is larger, go right. If it is equal, you are done.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(n, key):
if n is None:
return Node(key)
if key < n.key:
n.left = insert(n.left, key)
elif key > n.key:
n.right = insert(n.right, key)
return n
def search(n, key):
while n is not None:
if key == n.key:
return True
n = n.left if key < n.key else n.right
return False
root = None
for k in [4, 2, 6, 1, 3]:
root = insert(root, k)
print(search(root, 3)) # True
print(search(root, 5)) # FalseEach loop iteration moves down one level. The number of steps is therefore at most the height of the tree, so search, insertion and deletion all cost O(h), where h is the height.
In-order traversal
Visiting the left subtree, then the node, then the right subtree lists the keys in sorted order. This follows directly from the invariant. It also gives a simple way to test it.
def in_order(n):
if n is not None:
yield from in_order(n.left)
yield n.key
yield from in_order(n.right)
print(list(in_order(root))) # [1, 2, 3, 4, 6]If the output of an in-order traversal is not strictly increasing, the BST invariant has been violated somewhere. The last chapter of this tutorial builds on this idea.
What the invariant does not control
The invariant says where keys may go. It says nothing about the shape of the tree. The same set of keys can produce very different trees, depending on insertion order:
| Insertion order | Resulting shape | Height |
|---|---|---|
| 4, 2, 6, 1, 3 | Wide and short | 3 |
| 1, 2, 3, 4, 6 | A single chain to the right | 5 |
Both trees are valid BSTs. The second behaves like a linked list, and its operations cost O(n). The next chapter looks at this problem, and the chapters after it show how rotations, AVL rules and red-black rules keep the height small while preserving the invariant.
Exercise
You insert the keys 10, 20, 30, 40 into an empty BST in that order, using the insert function above. What is the height of the resulting tree, and what is the cost of searching for 40 in terms of n?
Show answer
Each key is larger than all previous keys, so each goes to the right of the last. The tree is a chain of 4 nodes, so its height is 4 (counting a single node as height 1). Searching for 40 visits every node, which costs O(n).
Exercise
A tree has root 8 with left child 3. Node 3 has a right child 9. Is it a valid BST? Explain using the invariant.
Show answer
No. The key 9 is in the left subtree of 8 but is larger than 8. The invariant applies to the whole subtree, so the tree is invalid even though 9 is correctly placed to the right of 3.