RB Tree
RB Tree
Definition
• A red-black tree is a binary search tree with one extra attribute for
each node: the color, which is either red or black.
• Red-black tree properties are:
1. Every node is either red or black.
2. Root and leaves (NULL) are black; if a node’s child is missing then we will
assume that it has a nil child in that place and this nil child is always colored
black.
3. If a node is red, then both its children are black. (red property)
4. Every simple path from a node to a descendant leaf contains the same
number of black nodes. (black property)
Example
Operations
1. Rotation
2. Insertion
3. Deletion
Rotations
To ensure that color scheme and properties of red-black trees don’t
get thrown off, they employ a key operation known as rotation.
Rotation is a binary operation, between a parent node and one of its
children, that swaps nodes and modifies their pointers while
preserving the inorder traversal of the tree (so that elements are still
sorted).
There are two types of rotations: left rotation and right rotation.
Left Rotation
Left rotation swaps the parent node with its right child.
Here are the steps involved in for left rotation:
1. Assume node x is the parent and node y is a non-leaf right child.
2. Let y be the parent and x be its left child.
3. Let y’s left child be x’s right child.
Example:
Right Rotation
Right rotation swaps the parent node with its left child.
Here are the steps involved in for right rotation:
1. Assume node x is the parent and node y is a non-leaf left child.
2. Let y be the parent and x be its right child.
3. Let y’s right child be x’s left child.
Insertion
• Let x be the newly inserted node.
1) Perform standard BST insertion and make the color of newly
inserted nodes as RED.
• 2) If x is root, change color of x as BLACK (Black height of complete
tree increases by 1).
• 3) Do following if color of x’s parent is not BLACK or x is not root.
….a) If x’s uncle is RED (Grand parent must have been black
from property 4)
……..(i) Change color of parent and uncle as BLACK.
……..(ii) color of grand parent as RED.
……..(iii) Change x = x’s grandparent, repeat steps 2 and 3 for new x.
b) If x’s uncle is BLACK, then there can be four configurations for x, x’s
parent (p) and x’s grandparent (g) (This is similar to AVL Tree)
……..i) Left Left Case (p is left child of g and x is left child of p)
……..ii) Left Right Case (p is left child of g and x is right child of p)
……..iii) Right Right Case (Mirror of case i)
……..iv) Right Left Case (Mirror of case ii)
Left Left Case (p is left child of g and x is left
child of p)
Left Right Case (p is left child of g and x is
right child of p)
(p is right child of g and x is right child of p)
(p is right child of g and x is left child of p)
Exercise:
Insert 2, 1, 4, 5, 9, 3, 6, 7 in RB Tree