Left Leaning Red-Black BSTs (LLRB tree)
Red-Black Tree
- Represent 2-3 tree as a BST
- Use internal left-leaning links as glue for 3-nodes
-image1-382af282d34969d46c9dbe8139242bea.jpg)
Properties
- No node has two red links connected to it
- Every path from root to null link has the same number of black links
- Red links lean left
Operations
Search
-image2-e2f6ee6af3612280cc95aa018e1fa013.jpg)
Implementation
-image3-938454589fded8792df7a7cded438972.jpg)
Left rotation - Orient a (temporarily) right-leaning red link to lean left
-image4-72969f29131673fe6fb0b286ae18efe8.jpg)
Right rotation - Orient a left-leaning red link to (temporarily) lean right
-image6-4a8c1b41636fd67709eb114cdfed6c88.jpg)
Color flip - Recolor to split a (temporary) 4-node
-image8-284918fc86f89c7c5ee44133bb7d4c00.jpg)
-image9-7b0a8a64a53c105cffe3191b4421bcf0.jpg)
Insertion in a LLRB tree
Basic Strategy
-image10-3ae4427e11f9bd89b9d928dd533448d5.jpg)
Insert into a tree with exactly 1 node
-image11-c1b2757843e1812126b02610f025ce95.jpg)
- Insert into a 2-node at the bottom
- Do standard BST insert; color new link red
- If new red link is a right link, rotate left
-image12-5394efdf4d1f59f819da7b97f71a7c78.jpg)
Insert into a tree with exactly 2 nodes
-image13-5cf51f722f5bfb91d857b207b57006af.jpg)
- Insert into a 3-node at the bottom
- Do standard BST insert; color new link red
- Rotate to balance the 4-node
- Flip colors to pass red link up one level
- Rotate to make lean left
- Repeat case 1 or case 2 up the tree
-image14-f7885073e3439888e3a3e62f35851c6b.jpg)
-image15-15b51070f8986cfc4db7713bfae331c0.jpg)
Insertion Code
-image16-ce9af30ffe601f3677251da481a3d29c.jpg)
If implemented properly, the height of a red-black BST with N keys is at most 2 lg N
-image17-7e9854b852b798edab57045272c78483.jpg)
Applications
Red-black trees are widely used as system symbol tables
- Java: Java.util.TreeMap, java.util.TreeSet
- C++ STL: map, multimap, multiset
- Linux kernel: completely fair scheduler, linux/rbtree.h
- Emacs: conservative stack scanning