Learn Before
Concept
Red-Black Tree
Red-Black trees are a type of Binary Search Tree that use color identifiers and rotations to balance themselves, maintaining a search time of O(logn). In a Red-Black tree, every node is assigned a color bit to identify it as red or black. There are three major rules this data structure follows:
- Every root node is black
- All red nodes have black children
- The path from the root to the end of the tree contains an equal number of black nodes
Inserting nodes into a Red-Black tree may require recoloring and/or a rotation, similar to rotations found in AVL trees. The insertion algorithm and recoloring is covered below:
- If the tree is empty, insert a new node and color it black.
- Otherwise, insert a new leaf node to the end and color it red.
- If the parent node is red and its neighbor (the uncle of the inserted node) is also red, a recoloring must be done. The color of the uncle, parent, and grandparent node must be flipped.
- If the parent node is red and its neighbor (the uncle of the inserted node) is null/black (all null nodes are treated as black), then a rotation must be performed on the inserted node and the parent. For the last step, it's possible a Left or Right rotation would be performed. This depends on which rotation would ultimately balance the tree and maintain the rules of coloring. In some cases, even after a rotation, additional rotations or recolorings will be performed until the tree is fully balanced.
0
1
Updated 2021-05-24
Tags
Python Programming Language
Data Science