BALANCED SEARCH TREES
2-3 trees. Understand how to search and insert.
Understand why insertion technique leads to perfect balance and symmetric order.
Terminology. Symmetric order. Perfect balance.
Performance of 2-3 trees. Tree height is between log_3 N and log_2 N. All paths are of the same height.
1-1 correspondence between LLRBs and 2-3 trees. Understand how to map a 2-3 tree to an LLRB and vice versa.
LLRBs. BST such that no node has two red links touching it; perfect black balance; red links lean left.
LLRB get. Exactly the same as regular BST get.
Storing color. A node's color is the same as the edge connecting that node to its parent.
LLRB insert. Insert as usual, then apply rotations recursively as follows, working upwards from the new node.
- Case 3: A parent node has a black left child and a red right child, so rotate the parent left.
The former right child is now the boss. Reminder: null links are considered black for the purposes of deciding cases.
- Case 2: A grandparent node has a red left child whose left child is also red.
Rotate this grandparent right (so that one in the middle is now the boss).
- Case 1: A parent node has two red children. Flip colors.
Conveniently, we can always apply case 3, case 2, then case 1 to every node in a tree,
and we can guarantee that the entire tree will be an LLRB.
LLRB performance. Perfect black balance ensures worst case performance for get and insert is ~ 2 log_2 N.
Recommended Problems
C level
- Given an LLRB, is there exactly one corresponding 2-3 tree? Given a 2-3 tree, is the exactly one corresponding LLRB?
- Draw a 2-3 tree with all 3 nodes. Why is the height log3(N)?
- How many compares does it take in the worst case to decide whether to take the left, middle, or right link from a 3 node?
- Fall 2010 Midterm, #4. Fall 2011 Midterm, #6. Spring 2012 Midterm, #5. Spring 2013 Midterm, #2. Fall 2008 Midterm, #6. Fall 2009 Midterm, #4.
B level
- For a 2-3 tree of height h, what is the best case number of compares to find a key? The worst case?
A level
- Show that in the worst case, we need to perform order log N LLRB operations
(rotation and color flipping) after an insert (not as hard as it might seem).
Give an example of a tree which requires log N LLRB operations after a single insert (also not so hard).