Red-Black Tree

Red-Black Tree

A red-black tree is a self-balancing binary search tree that maintains balance by assigning colors (red or black) to its nodes and applying a set of rules to ensure balance. It was introduced by Rudolf Bayer in 1972.

To ensure balance in a red-black tree, a set of rules or properties are followed:


Root Property:

The root node of the tree is always colored black. This ensures that the black depth property holds for the entire tree.


Red Property:

Red nodes can only have black children. In other words, a red node cannot have a red child. This property prevents two consecutive red nodes on any path in the tree, which helps maintain balance.


Black Depth Property:

The number of black nodes on any path from a node to its descendant leaf nodes is the same for all paths in the tree. This property ensures that the tree is balanced in terms of black node counts.


External (Null Leaf) Property:

Null leaf nodes (or "external" nodes) are considered to be black. These nodes represent the leaf nodes in the tree and do not contain any data. They are necessary to maintain the black depth property.


By following these rules, the red-black tree ensures a balanced structure that guarantees a worst-case height of O(log n), where n is the number of nodes in the tree. This balanced structure allows efficient operations such as search, insertion, and deletion with a logarithmic time complexity.

During insertion and deletion operations, the red-black tree may need to be adjusted to maintain these properties. This involves performing rotations and color changes on nodes to balance the tree and satisfy the red-black tree rules. The specific adjustments and operations depend on the situation and the violation of the properties.

Overall, the set of rules in a red-black tree ensures a balanced structure by controlling the colors of nodes and maintaining a consistent black depth across all paths. This balance allows for efficient and predictable performance in various operations on the tree.