Red-Black Trees Related to a Binary Tree, but there are rules to help keep it balanced. Balanced Tree: Each node has the same number of descendents on the left as it has on the right Red-Black Characteristics 1. The nodes are colored 2. During insertion and deletion, rules are followed that preserver various arrangements of these colors. Red-Black Rules 1. Every node is either red or black 2. The root is always black 3. If the node is red, its children must be black 4. Every path from the root to a leaf, or to a null child, must contain the same number of black nodes Red-Black Actions When the Rules are Violated 1. Change the colors of the nodes 2. Perform rotations To minimize complications, duplicate node values are not permitted. Inserting into a Red-Black Tree Inserting is the same as a Binary tree, moving left if the value is smaller than the node and moving right if the value is larger. The process is compilcated by the necessity of doing color flips on the way down. New nodes are always red. If, in our travels, we find a black node with two red children, we must change the children to black and the current to red (unless the parent is the root). Rule 1 is not violated. Rule 2 is not violated. Rule 3 may be violated if the current node's parent is red, because we'll now have two reds in a row. This problem is resolved through rotations (discussed later) Rule 4 is not violated. Some terminology first: G = Grandparent P = Parent N = New An outside grandchild (left child) / G / P / N An inside grandchild (right child) / G / P \ N An inside grandchild (left child) / G \ P / N An outside grandchild (right child) / G \ P \ N Rotations on the way down: For an outside grandchild: 1. Switch the color of N's grandparent (G) 2. Switch the color of N's parent (P) 3. Rotate right with N's grandparent (G) For an inside grandchild: 1. Switch the color of N's grandparent (G) 2. Switch the color of N 3. Rotate left with N's parent (P) 4. Rotate right with N's grandparent (G) Rotations once the node is inserted: If parent is black, the insertion is complete If parent is red and N is outside, same as above for outside grandchild If parent is red and N is inside, same as above for inside grandchild Deletion from a Red-Black Tree Very complicated process. Generally, the node is marked with a boolean flag.