【Introduction to the red-black tree】

A red-black tree is a binary search tree where each node has a color attribute, either red or black. In addition to the general requirements enforced by binary search trees, we add the following additional requirements for any valid red-black tree:

Properties 1. Nodes are red or black.

Property 2. The root node is black.

Property 3 Each leaf node (NIL node, empty node) is black.

Property 4 Both children of each red node are black. (There cannot be two consecutive red nodes on all paths from each leaf to the root)

Property 5. All paths from any node to each of its leaves contain the same number of black nodes.

These constraints enforce a key property of red-black trees: the longest possible path from the root to a leaf is no more than twice as long as the shortest possible path. The result is that the tree is roughly balanced. Because the worst-case time for operations such as inserting, deleting, and finding a value is required to be proportional to the height of the tree, this theoretical upper bound on height allows red-black trees to be efficient in the worst-case, unlike ordinary binary search tree.



 

 

The key to inserting a node is:

Inserting a new node is always a red node

If the parent node of the inserted node is black, the property can be maintained

If the parent node of the inserted node is red, the property is destroyed. Therefore, the insertion algorithm is to maintain the property by recoloring or rotating



 

 

The key to deleting a node is:

If the red node is deleted, the property is not destroyed

If the black node is deleted, then there will be one less black node on the path, destroying the property. Therefore, the deletion algorithm is to maintain the property by recoloring or rotating

 

 

The inclusion of "double-black" nodes is clearly not a requirement for a red-black tree, so this must be eliminated. There are four types of "double black" situations:  

1. The sibling node of the double black node is red  

2. The sibling of a double black node is black, and its sibling has two black children  

3. The brother of the double black node is black, and the left and right child nodes of its brother are red and black respectively  

4. The sibling of a double-black node is black, and the right child of its sibling is red  

Obviously, the above four situations include all possible situations.  

The basic idea of ​​dealing with double black nodes is to perform "color compensation". In other words, turn the adjacent red node into black, and at the same time, the double black node is also "restored" to black.  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326252999&siteId=291194637