4
4 Ruli Manurung (Fasilkom UI)IKI10100: Lecture Red-Black Trees: Definition Rules of Red-Black Trees: 1. Every node is colored either red or black 2. The root is black 3. If a node is red, its children must be black consecutive red nodes are disallowed 4. Every path from a node to a null reference must contain the same number of black nodes Convention: null nodes are black

6
6 Ruli Manurung (Fasilkom UI)IKI10100: Lecture Red-Black Trees: Properties Each path must contain the same number of black nodes. (Rule #4) Consecutive red nodes are not allowed. (Rule #3) The longest path is at most twice the length of the shortest path

8
8 Ruli Manurung (Fasilkom UI)IKI10100: Lecture Insertion A new node must be colored red Why? A new item is always inserted as a leaf in the tree If we color a new item black, then the number of black nodes from root would be different (violate property #4) If the parent is black, no problem. If the parent is red, we create two consecutive red nodes (violate property #3) Thus, we have to do some rotating/recolouring… Remember convention: null nodes are black

11
11 Ruli Manurung (Fasilkom UI)IKI10100: Lecture Single Rotation (bottom-up) Case after insertion: Consecutive red Sibling of parent is red Outer node (left-left or right-right) AB G X SP C DE AB G X S P C DE But what if P’s parent is red?  We have to keep going up the tree all the way to the root 

14
14 Ruli Manurung (Fasilkom UI)IKI10100: Lecture AB G X SP C DE Color Flip (2) AB G X SP C DE If we do the colour flipping on the way down to the insertion point, we will never reach a condition where P & S are red!

30
30 Ruli Manurung (Fasilkom UI)IKI10100: Lecture Case 2: One/Both of X’s children is red Recurse down to X’s child If we land on a red node, fine. If we land on a black node, rotate sibling and parent: B P S X A C C S P B X A D D

31
31 Ruli Manurung (Fasilkom UI)IKI10100: Lecture Red-Black trees use color as balancing information instead of height in AVL trees. An insertion may cause a local perturbation (two consecutive red nodes) The pertubation is either resolved locally (rotations), or propagated to a higher level in the tree by recoloring (color flip) O(1) for a rotation or color flip At most one restructuring per insertion. O(log n) color flips Total time: O(log n) Summary