Sub topic 1
Quick review: the binary search tree invariant
This chapter refreshes the one rule that every balanced tree in this tutorial must keep. AVL and red-black trees add extra rules for shape. The ordering rule underneath stays the same, and every later repair, rotation and test builds on it.
Prerequisites
This chapter assumes you already know the following:
- How to search, insert into and delete from a binary search tree (BST) at a basic level.
- Recursion, and the terms root, leaf, subtree and height.
- Big-O notation, including the difference between O(log n) and O(n).
- Enough Python to read classes, recursive functions and generators.
If any of these are shaky, the sections below give a compact refresher. They are not a first introduction.
The invariant
A binary search tree is a binary tree where each 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 whole subtrees, not just to the two children. Every descendant on the left is smaller than the node, however deep it sits.
In this tutorial, keys are unique. Inserting a key that already exists changes nothing. Other designs allow duplicates by choosing a side (for example, "equal keys go right"). Whatever you choose must be applied consistently, or search and deletion will disagree about where a key lives.
Why the invariant is useful
The invariant lets you throw away half the remaining candidates at each step. To find a key, compare it with the current node:
- If the key is smaller, only the left subtree can contain it.
- If the key is larger, only the right subtree can contain it.
- If the key is equal, you have found it.
The invariant also gives a second property. An in-order traversal (left subtree, then node, then right subtree) visits keys in sorted order. That fact is the basis of the validator at the end of this chapter, and of the invariant tests used later in the tutorial.
A reference implementation
The code below is the plain, unbalanced BST. The balanced versions in later chapters extend this code. It uses the same Node shape, the same recursive style, and the same deletion strategy based on the in-order successor.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def search(n, key):
while n is not None:
if key < n.key:
n = n.left
elif key > n.key:
n = n.right
else:
return n
return 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 # equal key: ignore the duplicate
def min_node(n):
while n.left:
n = n.left
return n
def delete(n, key):
if n is None:
return None
if key < n.key:
n.left = delete(n.left, key)
elif key > n.key:
n.right = delete(n.right, key)
else:
if n.left is None:
return n.right
if n.right is None:
return n.left
successor = min_node(n.right)
n.key = successor.key
n.right = delete(n.right, successor.key)
return n
def inorder(n):
if n is not None:
yield from inorder(n.left)
yield n.key
yield from inorder(n.right)
def height(n):
return 0 if n is None else 1 + max(height(n.left), height(n.right))
root = None
for k in [4, 2, 6, 1, 3, 5, 7]:
root = insert(root, k)
print(list(inorder(root))) # [1, 2, 3, 4, 5, 6, 7]
print(height(root)) # 3
root = delete(root, 4)
print(list(inorder(root))) # [1, 2, 3, 5, 6, 7]
print(root.key) # 5Notice the pattern n.left = insert(n.left, key). Each recursive call returns the root of the modified subtree, and the parent stores it. This convention matters a great deal later. A rotation changes which node is the root of a subtree, so the code must be able to hand a new root back up to the parent. The AVL code in the following chapters relies on this return-the-new-root style.
The three cases of deletion
Insertion always adds a new leaf, so it is simple. Deletion is where the invariant needs care. The node you remove has one of three shapes:
| Case | What to do | Why the invariant survives |
|---|---|---|
| No children (leaf) | Return `None` to the parent | Removing a leaf leaves all other keys in their places |
| One child | Return that child to the parent | The child's whole subtree already fits in the removed node's slot |
| Two children | Copy the in-order successor's key into the node, then delete the successor from the right subtree | The successor is the smallest key larger than the node, so it fits between the two subtrees |
The successor is the leftmost node of the right subtree. It has no left child, so deleting it falls into the leaf or one-child case. The in-order predecessor (the rightmost node of the left subtree) works equally well. The code above picks the successor, and the later chapters do the same.
Cost depends on height
Each step of a search, insertion or deletion moves one level down. The work is therefore proportional to the height h of the tree, which is the number of nodes on the longest root-to-leaf path. An empty tree has height 0, and a single node has height 1.
| Operation | Cost |
|---|---|
| Search | O(h) |
| Insert | O(h) |
| Delete | O(h) |
| Minimum or maximum | O(h) |
| In-order traversal | O(n) |
The tables above say O(h), not O(log n). The two are only the same when the tree is reasonably full. For n keys, the height can be anywhere from about log₂ n up to n, depending on the shape. The invariant fixes the order of the keys, but it does not fix the shape.
Shape depends on insertion order
The same set of keys can produce very different trees. This fragment uses the functions defined above.
balanced = None
for k in [4, 2, 6, 1, 3, 5, 7]:
balanced = insert(balanced, k)
skewed = None
for k in range(1, 8):
skewed = insert(skewed, k)
print(height(balanced)) # 3
print(height(skewed)) # 7
print(list(inorder(skewed))) # [1, 2, 3, 4, 5, 6, 7]Both trees satisfy the invariant, and both give the same sorted traversal. The skewed tree is a linked list leaning to the right, so each search may walk through every node. Sorted input is common in practice (timestamps, auto-incrementing IDs, data read from a sorted file), so this is not an exotic case.
The skewed tree also causes a Python-specific problem. The recursive insert uses one stack frame per level, so a skewed tree with a few thousand keys can exceed Python's default recursion limit of about 1000 and raise RecursionError. A balanced tree keeps recursion depth near log₂ n, which is another reason the next chapters matter.
Checking the invariant correctly
Later chapters use a validator to test rotations and rebalancing. Here is the check in its simplest form. It looks tempting to verify only that each node is larger than its left child and smaller than its right child. That check is wrong, as the example below shows.
def naive_check(n):
if n is None:
return True
if n.left is not None and n.left.key >= n.key:
return False
if n.right is not None and n.right.key <= n.key:
return False
return naive_check(n.left) and naive_check(n.right)
def is_bst(n, lo=None, hi=None):
"""True if every key in the subtree lies strictly between lo and hi."""
if n is None:
return True
if lo is not None and n.key <= lo:
return False
if hi is not None and n.key >= hi:
return False
return is_bst(n.left, lo, n.key) and is_bst(n.right, n.key, hi)
bad = Node(5)
bad.right = Node(8)
bad.right.left = Node(3) # 3 sits in the right subtree of 5
print(naive_check(bad)) # True (wrong)
print(is_bst(bad)) # False (correct)
print(list(inorder(bad))) # [5, 3, 8] not sortedIn bad, every parent-child pair looks fine locally: 3 is less than its parent 8. But 3 is in the right subtree of 5, so it breaks the rule. The invariant is about whole subtrees, so a correct check must carry the allowed range (lo, hi) down the recursion. Each step narrows the range: going left sets hi to the current key, and going right sets lo.
An equivalent check is to collect the in-order traversal and confirm it is strictly increasing. The range-based version is usually preferred because it stops at the first violation and reports exactly where it happened.
Common errors
- Checking only parent and child. As shown above, this misses violations that involve a grandparent or a more distant ancestor.
- Forgetting to store the returned subtree. Writing
insert(n.left, key)without assigning the result loses the new node whenever the left subtree was empty. - Mixing duplicate policies. If
insertignores duplicates but a test helper expects them on the right, the validator and the tree will disagree. - Deleting by copying a key but not removing the source node. After copying the successor's key into the node, you must still delete the successor from the right subtree, or the key appears twice.
- Assuming O(log n). A plain BST gives O(h). Only a balance guarantee turns h into log n.
What comes next
The next chapter measures how much damage a bad shape does, and why keeping the height near log₂ n is the goal. After that, rotations show how to reshape a subtree locally while preserving the invariant from this chapter. Every balanced tree later in the tutorial is a plain BST plus a rule about shape, so any rotation or recoloring is correct only if is_bst still returns True afterwards.
Exercise
Starting from an empty plain BST, you insert 10, 5, 15, 12, 20, then delete 10 using the in-order successor method. What is the root afterwards, and what is the in-order traversal?
Show answer
The node 10 has two children, so its in-order successor is the smallest key in its right subtree. The right subtree is rooted at 15, whose leftmost node is 12. Copy 12 into the root, then delete 12 from the right subtree (a leaf, so it is simply removed). The new root is 12, and the in-order traversal is [5, 12, 15, 20].
Exercise
A tree has root 10, a left child 5, and a right child 15. Node 5 has a right child 12. Every parent-child pair satisfies "left is smaller, right is larger". Is it a valid BST? Which call to is_bst first reports the problem, and with what bounds?
Show answer
It is not valid. The key 12 is in the left subtree of 10, but 12 is larger than 10. Every parent-child pair looks fine (12 is larger than its parent 5), so a local check passes. The call is_bst(node_12, 5, 10) reports the problem, because 12 >= hi (10), so it returns False.