Insertion in Red
Insertion in Red
Rules of Insertion:
1. If tree is empty create a node as root node with color black.
2. If tree is not empty create a leaf node with color Red.
3. If parent of new node is black then exit.
4. If parent of new node is Red then check the color of parent’s sibling of new node.
A) If color is black or null then do suitable rotation
and coloring.
B) If color is Red then recolor & also check if its
parent’s parent of new node is not root node then
recolor it and recheck.
Example:
Creating a red-black tree with elements 3, 21, 32 and 17 in an empty tree.
Why do we need Red Black Tree?
A BST may have a height of n( total number of nodes) in the most worst case if the elements are
in increasing or decreasing order. This would consign it to O(n) time for searches, insertions and
deletions. This is the reason we require a red-black tree. It keeps the BST balanced with a height
log n.
A red-black tree is a sort of elf-balancing binary search tree where every node has an additional
bit, and that bit is often interpreted as the color red or black. These colors are utilized to
guarantee that the tree remains balanced during insertions and deletions.