Why the shape matters
After this: Explain why sorted input makes a chain, what O(log n) means here, and what balanced trees guarantee.
On this page · 8 sections · 3 checks
Every search, insert and delete you have seen goes down one path from the root, with one comparison per level. So far our example tree has been short and wide, which keeps that path short. This lesson asks what happens when a tree is not short and wide.
Sorted keys make a straight line
Insert 10, 20, 30, 40, in that order, into an empty tree. Try drawing it before you read on.
- 10 goes in first, so it is the root.
- 20 is larger than 10, so it goes to the right of 10.
- 30 is larger than 10 and 20, so it goes to the right of 20.
- 40 is larger than all of them, so it goes to the right of 30.
The result is a straight line. It has four nodes and three edges (an edge is the link between a parent and a child), so its height is 3. Every node has at most one child. A tree in this shape is called a .
Searching for 40 compares 10, 20, 30 and 40: all of them. This is the same work as going through a list from the start. We have lost the thing that made a BST useful.
The same four keys in a different order give a shorter tree. Insert 20, 10, 30, 40, and the height is 2. Both trees follow the order rule, so the rule cannot stop this. The order of the inserts decides the shape.
The height sets the cost
Search, insert and delete each follow one path from the root, with one comparison per level. So the number of comparisons depends on the height. We write this as O(h), which means that the work grows with the height h.
The same seven keys show how far apart two trees can be.
| Insert order | Shape | Height | Comparisons to find 80 |
|---|---|---|---|
| 50, 30, 70, 20, 40, 60, 80 | bushy | 2 | 3 |
| 20, 30, 40, 50, 60, 70, 80 | chain | 6 | 7 |
A bushy tree is one with its levels nearly full, so it is short and wide. A chain with n keys has height n − 1, the tallest a tree can be. Sorted or nearly sorted keys are common in real data, such as dates or ID numbers that only go up. So this worst shape is not rare.
How short can a tree be?
Each level of a tree can hold twice as many nodes as the level above it: 1, then 2, then 4, then 8. So the space grows very quickly as you add levels.
| Full levels | Keys that fit |
|---|---|
| 1 | 1 |
| 2 | 3 |
| 3 | 7 |
| 4 | 15 |
| 10 | 1,023 |
| 20 | 1,048,575 |
So a bushy tree can hold a million keys in only 20 levels, and a search in it makes at most 20 comparisons.
The name for this kind of growth is the . log₂ n answers the question: how many times can you halve n before you reach 1? Eight halves three times (8, 4, 2, 1), so log₂ 8 is 3. A million halves about 20 times, so log₂ 1,000,000 is about 20.
A bushy tree has a height of about log₂ n. We say its cost is O(log n), which means that the work grows very slowly: when the keys double, the work goes up by about one comparison. The tutorial on binary search gets the same cost by halving a sorted array, and Counting steps compares it with O(1) and O(n).
| Keys | Chain: most comparisons | Bushy tree: most comparisons |
|---|---|---|
| 7 | 7 | 3 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
This is why saying "a BST is O(log n)" is only half true. A BST is O(h), and h is about log₂ n only when the tree is bushy.
The code
To measure the height, we ask each child for its height. A node's height is 1 more than the larger of the two answers.
def height(self): return self._height(self.root)
def _height(self, node): if node is None: return -1 # empty: -1, so a single node is 0 return 1 + max(self._height(node.left), self._height(node.right)) int height() { return height(root); }
private int height(Node node) { if (node == null) return -1; // empty: -1, so a single node is 0 return 1 + Math.max(height(node.left), height(node.right)); }An empty tree returns −1. This is what makes a single node come out right: 1 + (−1) = 0, and a tree of one node has height 0.
The next block builds the two seven-key trees. It prints the height of each one, and the length of the path to 80, which is the number of comparisons.
bushy = BST()for k in [50, 30, 70, 20, 40, 60, 80]: bushy.insert(k)chain = BST()for k in [20, 30, 40, 50, 60, 70, 80]: # the same keys, in sorted order chain.insert(k)print(bushy.height(), len(bushy.path(80))) # height, comparisons to find 80print(chain.height(), len(chain.path(80)))2 3 6 7
BST bushy = new BST();for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) bushy.insert(k);BST chain = new BST();for (int k : new int[] {20, 30, 40, 50, 60, 70, 80}) chain.insert(k); // the same keys, in sorted orderSystem.out.println(bushy.height() + " " + bushy.path(80).size()); // height, comparisons to find 80System.out.println(chain.height() + " " + chain.path(80).size());2 3 6 7
Watch it happen
Insert the four keys in sorted order, then search for the last one and measure the height. Afterwards, reset the card and run the preset. It inserts the same keys in the order 20, 10, 30, 40, which gives height 2.
- Insert 10Insert 10 into the empty tree. It becomes the root.
- Insert 20
- Insert 30
- Insert 40
- Search for 40
- Measure the height
empty
The tree is empty. Insert 10, 20, 30, 40 in that order and watch the shape.
What a balanced tree guarantees
A BST like ours never repairs its shape. It keeps whatever shape the inserts gave it. The fix is a tree that does repair itself.
A tree is when no part of it is much deeper than the rest, so its height stays close to the smallest possible. A is a BST that moves a few nodes after each insert or delete to keep itself balanced. These small moves are called rotations. The two common kinds are AVL trees and red-black trees.
The result is a guarantee you can rely on: the height stays O(log n), so search, insert and delete are O(log n) in the worst case, whatever order the keys arrive in. A red-black tree keeps its height to about twice the smallest possible height, and an AVL tree keeps it closer than that.
How rotations work needs a tutorial of its own. You do not need that to use the library versions well. You only need to know what they guarantee.
Check yourself
Insert 10, 20, 30, 40, in that order, into an empty tree. What is the height, and how many comparisons does a search for 40 make?
What does a self-balancing BST (an AVL tree or a red-black tree) guarantee?
The same seven keys are inserted in two orders. What does this print (the height, then the comparisons to find 80), for the bushy tree and then the chain?
bushy = BST()for k in [50, 30, 70, 20, 40, 60, 80]: bushy.insert(k)chain = BST()for k in [20, 30, 40, 50, 60, 70, 80]: # the same keys, in sorted order chain.insert(k)print(bushy.height(), len(bushy.path(80))) # height, comparisons to find 80print(chain.height(), len(chain.path(80)))BST bushy = new BST();for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) bushy.insert(k);BST chain = new BST();for (int k : new int[] {20, 30, 40, 50, 60, 70, 80}) chain.insert(k); // the same keys, in sorted orderSystem.out.println(bushy.height() + " " + bushy.path(80).size()); // height, comparisons to find 80System.out.println(chain.height() + " " + chain.path(80).size());Connect
- Show that inserting sorted keys makes a chain of height n − 1, so a search does the work of going through a list.
- Say that every BST cost is O(h), and what h is for a bushy tree and for a chain.
- Say what log₂ n means: how many times n can be halved before reaching 1. A million keys fit in 20 full levels.
- Say what a self-balancing tree guarantees: its height stays O(log n), so its operations are O(log n) in the worst case.