Sub topic 12
Degenerate Trees and the Sorted-Input Problem
This chapter assumes you know the binary search tree (BST) ordering property and can read the Node and insert code from earlier chapters. You should also be comfortable with Big-O notation and recursion.
Why shape matters
Search, insert, and delete each walk a single path from the root down. Their cost is proportional to the tree's height, the number of edges on the longest root-to-leaf path. The number of keys, n, does not set the cost directly.
A BST built from the same keys can have very different shapes. The shape depends on the order in which you insert them. A degenerate tree is a tree where every node has at most one child, so it behaves like a linked list.
The same keys, two shapes
The code below reuses Node and insert from the earlier chapter. It builds two trees from the same five keys and measures their heights.
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 height(node):
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
balanced = None
for k in [3, 1, 5, 2, 4]:
balanced = insert(balanced, k)
chain = None
for k in [1, 2, 3, 4, 5]:
chain = insert(chain, k)
print(height(balanced)) # 2
print(height(chain)) # 4An empty tree has height -1 in this code, so a single node has height 0.
What happens with sorted input
Insert 1, 2, 3, 4, 5 in that order. Each new key is larger than everything already in the tree. It goes to the right of the rightmost node every time. The left references are never used.
Reverse-sorted input gives the mirror image, a chain of left children. Every insertion must walk the whole existing chain before it adds a node. Building the tree from n sorted keys therefore costs 1 + 2 + ... + n steps, which is O(n²).
Cost by shape
| Shape | Height | Search, insert, delete |
|---|---|---|
| Balanced (about equal subtrees) | about log₂ n | O(log n) |
| Degenerate (chain) | n - 1 | O(n) |
For n = 1,000,000, a balanced tree needs about 20 steps per operation. A chain can need up to 1,000,000. At that point the BST has no advantage over scanning a linked list.
Beyond perfectly sorted input
Strictly sorted input is the worst case, but nearly sorted data causes the same trouble. Common examples are:
- Timestamps or auto-increment IDs inserted as they arrive.
- Data loaded from a file that was sorted earlier.
- Long runs of increasing keys with a few out-of-order values.
These inputs produce trees that are tall and stringy, even when they are not perfect chains.
Random insertion order behaves much better. The expected height of a BST built from random keys is O(log n). This is an average-case result. It does not protect you when you cannot control the input order.
Practical mitigations
- Shuffle before bulk loading. If you have all keys up front, randomizing the order restores the expected O(log n) height.
- Build from sorted data directly. Pick the middle key as the root, then recurse on each half. This gives a minimum-height tree.
- Use a self-balancing tree. AVL and red-black trees rotate nodes during insert and delete to keep the height O(log n) whatever the order. The next chapters cover them.
Exercise
You insert the keys 10, 20, 30, 40, 50, 60, 70 into an empty BST in that order. What is the tree's height, and what is the cost of a search for 70? Name an insertion order of the same keys that gives height 2.
Show answer
Each key is larger than all earlier keys, so every key becomes a right child. The tree is a chain of 7 nodes with height 6. Searching for 70 compares against all 7 nodes, which is O(n). Inserting 40, 20, 60, 10, 30, 50, 70 gives a perfectly balanced tree of height 2.
Exercise
Why does random insertion order usually give a shallow tree, while sorted order does not?
Show answer
With random order, each new key is about equally likely to fall in any gap among the existing keys. The tree therefore grows in both directions, and its expected height is O(log n). With sorted order, every new key is the largest so far and always goes to the same side, which produces a chain.