Documente Academic
Documente Profesional
Documente Cultură
Data Structures
Dana Shapira Lecture #11 Red-Black Trees
1. The root is black. 2. The leaves are black. 3. Both children of a red node are black. 4. Every root-to-leaf path contains the same number of black nodes.
The black-height of a node x is the number of black nodes on a path from, but not including, x to a leaf. The black-height of T is the black-height of its root.
Element to insert: 21
parent[parent[x]] ? parent[x] x
Recoloring
1.
Recoloring
3.
3 cases: Both parent[x] and its sibling are red parent[x] is red, its sibling is black, and x is the left child of its parent As Case 2; but x is the right child of its parent
parent[x] x
Case 1
3.
3 cases: Both parent[x] and its sibling are red parent[x] is red, its sibling is black, and x is the left child of its parent As Case 2; but x is the right child of its parent
parent[x] x
Case 1
parent[parent[x]] parent[parent[x]]
Recoloring Right-rotation
Recoloring + Right-rotation
parent[x]
x Case 2
parent[x] x
Case 2
Recoloring
parent[parent[x]]
Left-rotation
Recoloring + Right-rotation
parent[x] x
Case 3 Case 2
Lemma: An insertion into a red-black tree with n nodes takes O(log n) time and performs at most two rotations.
Element to delete: 25
Element to delete: 25
Element to delete: 18
First step: Declare the child of the removed node doubly black.
Element to delete: 18
First step: Declare the child of the removed node doubly black.
x c w
1. 2. 3.
Case 1
c c c'
Left-rotation
c'
Case 2
Assume that x is the left child of its parent and that its right sibling w is black. parent[x] c
3 cases, depending on colors of children of w: Both are black Right child is red Left child is red, and right child is black Recoloring
x c
w (old) w x w (new)
1. 2. 3.
Case 1
Case 4
parent[x] c x w
Recoloring
c
Right-rotation
Observations: Cases 2 and 3 perform at most two rotations; then were done Case 1 only recolors and brings us one step closer to the root Case 4 performs one rotation and bring us one step away from the root! But then Cases 2 and 3 finish as before If Case 1 applies after the rotation, the next iteration exits because parent[x] is red Lemma: A deletion from a red-black tree with n nodes takes O(log n) time and performs at most three rotations.
Case 3
Case 2
Red-Black TreesSummary
Red-black trees support all dictionary operations in O(log n) time: Insert Delete Find Predecessor Successor Minimum Maximum