RedBlack Tree Neil Tang 02072008 CS 223 Advanced
Red-Black Tree Neil Tang 02/07/2008 CS 223 Advanced Data Structures and Algorithms 1
Class Overview Ø Definition Ø Tree height Ø Rotation and color flip Ø Insert Ø Delete CS 223 Advanced Data Structures and Algorithms 2
Definition A red-black tree is a special binary search tree in which Ø every node is either red or black; Ø the root is black; Ø every leaf (null) is black; Ø if a node is red, then both its children are black; Ø every simple path from a node to a descendant leaf contains the same number of black nodes. CS 223 Advanced Data Structures and Algorithms 3
Height Ø Theorem: A red-black tree with N nodes has height at most 2 log(N+1). (pp. 274 Cormen’s book) Ø Experiments suggests that the average red-black tree is about as deep as an average AVL tree. Ø The rotation happens less frequently. CS 223 Advanced Data Structures and Algorithms 4
An Example CS 223 Advanced Data Structures and Algorithms 5
Rotation if S is Black CS 223 Advanced Data Structures and Algorithms 6
Color Flip if S is red CS 223 Advanced Data Structures and Algorithms 7
Example: Insert 45 CS 223 Advanced Data Structures and Algorithms 8
Insert CS 223 Advanced Data Structures and Algorithms 9
Insert CS 223 Advanced Data Structures and Algorithms 10
Insert CS 223 Advanced Data Structures and Algorithms 11
Delete 15 5 3 Case 1: 15 16 12 10 5 20 18 13 23 Case 2: 5 3 15 20 13 23 18 12 10 20 23 13 6 7 15 5 16 12 10 15 5 7 Case 3: 18 7 16 6 3 20 12 6 12 10 3 10 6 7 16 6 20 13 18 23 3 10 CS 223 Advanced Data Structures and Algorithms 16 12 6 7 15 5 20 13 18 23 7 12
Delete Ø In terms of deletion, everything boils down to delete a leaf. Ø Deletion of a red leaf is trivial. Ø How to delete a black leaf: Change the color of the leaf to be deleted to red by a top-down pass. CS 223 Advanced Data Structures and Algorithms 13
Three Cases When X Has Two Black Children CS 223 Advanced Data Structures and Algorithms 14
- Slides: 14