Algorithm--Introduction of red and black Tree Implementation (II.)

Source: Internet
Author: User

I. Overview

In the previous article, we reviewed the characteristics of red-black tree and added processing, we can learn that the red and black tree is a binary search tree, on the basis of the increase in the color of the node constraints to make the red and black trees approximate balance. When we add or remove nodes, we need to adjust the tree so that it satisfies the red-black tree again. This involves changing the color of the node and the rotation of some nodes. We've covered the rotation of the nodes and the processing of the additions, so this article focuses on the removal of red and black trees.

Ii. characteristics of red and black trees

In the introduction of the deletion, we would like to review the red and Black Tree Five features, as follows:

1) The color of the node is red or black

2) The root node of the tree is black

3) The leaf node of the tree is black

4) If the color of a node is red, then its two son node must be black

5) Two subtrees of any node, and the number of black nodes in each path is equal.

After the deletion of the node, these 5 properties may be destroyed, so after deletion, you also need a series of processing to make the whole tree into a red black tree.

Third, the red and black tree removal process

Red and black tree deletion algorithm mainly has three steps

3.1 Find the node to be deleted, this is a binary search tree lookup process, relatively simple.

3.2 In the case of finding the node, depending on the child's situation, it can be divided into three different situations:

1) The node has two children of non-leaf nodes

2) The node has a child with a non-leaf node

3) The node is only a leaf node

Here, what we call the leaf node refers to the empty node. So according to these three cases, we need to do different processing.

For scenario 1, we need to find the successor node of the current node, which is defined as the node's subtree, the first node that has no left child (or left child as leaf node). Once the node is found, we need to synchronize the value of the node to the current node, and instead delete its successor.

The advantage of this is that the successor node may have at most one child (and the right child). Because according to the definition of the successor node, the left child must be a leaf node. So for its subsequent nodes to do the deletion process, there will be no situation 1 exists, and there will only be conditions 2 and 3 exist.

We can demonstrate the following by:

    

Through the above processing, we will delete the deletion to node 24, but after 24 delete its data is not, so we put its content to the original node to be deleted, 22.5.

For Case 2, the deleted node has a child, we need to find its only son, and remove the deleted node from the tree, and the only son as the starting point to be processed, to make a tree adjustment.

As follows:

For Case 3, we directly put the current node as the starting point of the tree's red-black property adjustment, only after the adjustment, because the node has not been deleted before, so the current node needs to be removed.

3.3 Adjusting the tree after deleting a node

After the node is deleted, the red and black nature of the tree may be destroyed and we need to adjust the tree when it is destroyed. So, let's make it clear that the nature of the red and black tree may be destroyed after a node is deleted.

A) When the deleted node is red, for example, 27, this time the number of black nodes in the path will not change, that is, the nature of 5 will not be destroyed, because it is a red node, so its father must be black, so there will not be a parent-child is red, so the nature of 4 will not be destroyed In addition, the red node must not be the root node, so the nature of 2 will not be destroyed; In addition the Properties 1 and property 3 cannot be changed.

Therefore, when deleting a red node, the 5 properties of the tree will not change, the tree is still a red-black tree, do not need to do any processing.

b) When the deleted node is black, some of the following conditions may occur.

B1) When the root node is deleted, and the root node has only one red son, then the red son of the node becomes the only node in the tree and is red, which destroys the Nature 2.

B2) When a non-root node is deleted, the node must have a sibling node, or else because the node is located in a path that has more black nodes than the other branch. That's why, if the node is deleted, the number of black nodes in that node's branch is 1 less than the number of black nodes on the path where the sibling node resides. So the non-root node of the case, the nature of 5 will certainly be destroyed.

B3) When the node is deleted from a non-root node, and the parent-child is a red node, the child of the node becomes the parent node of the node after the current one is deleted. such as the desired nodes 24 and 25.

  

Because of these three cases, we need to restore the red-black nature of the tree when the deleted node is black. We divided the above situation into two parts, that is, the deleted node is not the root, so as to separate processing. If the root is better to deal with, in this case, if there is a red son to turn the red Son Black will end, no red son do not have to do anything.

So for the non-root situation is more complicated, said earlier, in this case, there are two inferences, that is, the number of black nodes is 1 less than the other path, and the node must have a sibling node. We can also make adjustments based on this premise. The caller of the red and black tree gives an algorithm that receives a node as the starting node for the adjustment, which says that the node may be a child node of the node being deleted, or it may be the node itself (in the absence of a son node).

In order to facilitate the loop processing, the algorithm assumes that the current input node is located in the subtree is satisfied with the red black tree, but we know that the input node is located in the path of the number of black nodes 1 less than other paths, in order to solve this problem, the algorithm assumes that the current node has a special, the node and other ordinary nodes, more than The node may be "black" or "red-black", which erases the problem of 1 less black nodes. But this hypothesis is just for the sake of understanding, not really having this color, in this hypothetical condition, we can make some adjustments to make the whole tree satisfy the red and black, and the lack of this heavy black to complement back.

Based on this premise, the algorithm gives a solution to several possible situations.

[1]. Input node is red, sibling node color arbitrary

This is relatively simple, directly turn the node into black, as follows:

[2] Input node is black

[2.1] Brother node for red

In this case, it is clear that the brother's father and son are all black. This time we have to find a way to turn the brother node into black, a better solution is to make a left-hand rotation in the parent node, so that the left child of the original sibling node becomes the Father node of the right child, that is, the brother of the node, the realization of the Brother node from the red node to the Black node transformation.

Before the rotation, you need to turn the sibling node into black, the original Father node into red, in order to maintain the number of black nodes unchanged. Examples are as follows:

After the conversion is complete, the sibling node becomes black, the current node position remains unchanged, and continues processing.

[2.2] Brother node for black

[2.2.1] The two sons of the brothers node are all Black

In this case, since the brother's two sons are all black, we have the chance to set the sibling to red and set the current node as the Father node to continue the algorithm. In this way, the parent node has this magical feature, because it has a heavy black, so although the brothers turned red, but the brother branch of the number of black nodes unchanged, because the original input node is no longer a special node, so the original input node has lost the original more heavy black, So the number of black nodes in the path of the original input node remains the same, indicating that this processing does not affect the nature of the red and black trees. However, we have raised the current node to the parent node, and if this is the case, it will be able to end with the root node.

The diagram for this process is as follows:

As shown, if [2.1.1] is converted from [2.1] by rotation, the current node becomes a red node, and the next time it is processed, it will be flushed directly.

If two sons are not all black, one of the children of the sibling node will be red. In, in order to achieve erase node 24 in the extra heavy black, we want to keep the parent node color unchanged on the basis of the addition of a black node, to do this, the parent node must be a pivot to the left rotation, so that node 24 will fall one level, the path on which a new node will be added. Because of the left-hand, and the need for artificial addition of a black node, will inevitably lead to the original sibling node color changes in the path, in order to facilitate coloring, we need the brother node of the right child red.

If the right child of the sibling node itself is red, of course, directly processing can, if the right child is black, then the left child will be red, for this situation, we need to do more rotation.

[2.2.2] Brother node left child is red, right child is black

In this case, according to the previous analysis, we have to do a rotation to make the right child red, this is also relatively simple, the operation is as follows:

This completes the process of the sibling node's left child to red to the right child. When the right child is red, it is possible to deal with the above discussion.

[2.2.3] Brother node right child for red, left child color arbitrary

In this case, we said earlier that we have to find a way to add a black node to the path where the current node is located, so we want to turn the parent node to the left and change the color of some nodes, as follows:

Turn the parent node black (this is the new node)

Change the color of the sibling node to the color of the parent node (when the parent node is left, the sibling node is moved up to the new Father node, so it inherits the color of the original parent node) to compensate for the move Down

The Brother node's right son color becomes the color of the sibling node (the Brother node is black, so the right son is naturally also black) to compensate for the problem of the sibling node color loss.

Here are the illustrations:

    

Through the above processing, we will find that in addition to the current node 24 is the path of the number of black nodes increased, the number of black nodes of the other paths remain consistent, so that the current node's

The extra heavy black is removed, and the whole tree is re-preserved in the red-black tree.

At this point, the entire post-deletion node adjustment is over.

Iv. code Examples

This gives the TreeMap about node deletion.

4.1 Deleting a node

This section is a method for deleting nodes, not including adjustments, as follows:

Private voidDeleteEntry (entry<k,v>p) {Modcount++; Size--; //If strictly Internal, copy successor ' s element to P and then make P//Point to successor.        if(P.left! =NULL&& P.right! =NULL) {            //in this case, the successor node is found,entry<k,v> s =successor (p); //Store the value of the successor nodeP.key =S.key; P.value=S.value; //The p pointer points to the successor node, and the subsequent node is removedp =s; } //P has 2 children//Start fixup at replacement node, if it exists. //the son node of the successor node, there may only be oneentry<k,v> replacement = (P.left! =NULL?p.left:p.right); //because P has only one child, so you don't have to deal with two of them.        if(Replacement! =NULL) {            //If you have a child, delete the nodeReplacement.parent =p.parent; if(P.parent = =NULL) Root=replacement; Else if(p = =p.parent.left) P.parent.left=replacement; ElseP.parent.right=replacement; P.left= P.right = P.parent =NULL; //if the removal of the red node is irrelevant, no processing, if it is a black node to deal with            if(P.color = =BLACK) fixafterdeletion (replacement); //start adjusting from the deleted son node}Else if(P.parent = =NULL) {//return If we are the only node.Root =NULL;//The root node was deleted}Else {            //No Children.            Use the self as Phantom replacement and unlink. //that is, there is no left node and no right node, which is itself as a parameter node            if(P.color = =BLACK) fixafterdeletion (p); //Delete itself            if(P.parent! =NULL) {                if(p = =p.parent.left) P.parent.left=NULL; Else if(p = =p.parent.right) P.parent.right=NULL; P.parent=NULL; }        }    }

4.2 Specific adjustment operations

  

1 /**From CLR*/2     Private voidFixafterdeletion (entry<k,v>x) {3          while(x! = root && colorof (x) = =BLACK) {4             if(x = =Leftof (Parentof (x))) {5                  //x for left child6                 //Brother Node7entry<k,v> SIB =Rightof (Parentof (x));8 9                 //2.1 Brother node is red, then by adjusting, turn the brother node blackTen                 if(Colorof (SIB) = =RED) { One                      ASetColor (SIB, BLACK);//brother node turns black -SetColor (Parentof (x), RED);//parent node turns red -Rotateleft (Parentof (x));//Rotate Right theSIB = Rightof (Parentof (x));//Redefining sibling Nodes -                 } -  -                 //2.2 Brother node is black +                 if(Colorof (Leftof (sib)) = = BLACK && -Colorof (Rightof (sib)) = =BLACK) { +                      //the two sons of the 2.2.1 brothers are all Black. ASetColor (SIB, RED);//brother node turns red atx = Parentof (x);//The current node moves up -}Else { -  -                     if(Colorof (Rightof (sib)) = =BLACK) { -                         //2.2.2 Sibling node's right child is black, you want to adjust it to red -SetColor (Leftof (SIB), BLACK);//left child set to black inSetColor (SIB, RED);//Brother node set to red -Rotateright (SIB);//right-handed to the sibling node toSIB = Rightof (Parentof (x));//Redefining sibling Nodes +                     } -  the                     //the right child of the 2.2.3 Brothers node is red *SetColor (Sib, Colorof (Parentof (x)));//The color of the brother node becomes its father's color $SetColor (Parentof (x), BLACK);//Father node's color turns blackPanax NotoginsengSetColor (Rightof (SIB), BLACK);//Brother Node's right son turns black -Rotateleft (Parentof (x));//The parent node is left-handed thex = root;//the entire tree has been restored to a red-black tree, x = root, ending the loop.  +                 } A}Else {  the                 //symmetric Operation +entry<k,v> SIB =Leftof (Parentof (x)); -  $                 if(Colorof (SIB) = =RED) { $ SetColor (SIB, BLACK); - SetColor (Parentof (x), RED); - rotateright (Parentof (x)); theSIB =Leftof (Parentof (x)); -                 }Wuyi  the                 if(Colorof (Rightof (sib)) = = BLACK && -Colorof (Leftof (sib)) = =BLACK) { Wu SetColor (SIB, RED); -x =parentof (x); About}Else { $                     if(Colorof (Leftof (sib)) = =BLACK) { - SetColor (Rightof (SIB), BLACK); - SetColor (SIB, RED); - Rotateleft (SIB); ASIB =Leftof (Parentof (x)); +                     } the SetColor (SIB, Colorof (Parentof (x))); - SetColor (Parentof (x), BLACK); $ SetColor (Leftof (SIB), BLACK); the rotateright (Parentof (x)); thex =Root; the                 } the             } -         } in  theSetColor (x, BLACK);//x must be black, because x may be a red node, or it may be root the}

The above code also provides a complete description of the previous deletion of the corresponding logic, if the previous diagram understanding, believe that the code is very easy to understand.

V. Summary

At this point, the removal of the red and black tree has been introduced, relative to the addition, this relatively more complex. But as long as the core of the idea, as well as the operation of the left and right rotation is very familiar with, also can understand. Once again summarize the main idea of deletion:

1. First to determine whether the current node has two children, if there is a need to find its direct successor, the successor must be no more than one child node, and then delete its successor

2. Delete repair from the deleted node's son node, when the son node is red, black can be directly, if it is black, you need to combine the color of their sibling nodes for analysis.

3. If the color of the sibling node is red, you need to turn the sibling node's color into black and rotate the tree to adjust.

4. If the sibling node color is black, then the color of its son node is processed

4.1 If the two sons are black, the brother turns black, and the current node points to the Father node

4.2 If the right son is black, you need to change the right son to red by adjusting

4.3 If the right son is red, it is adjusted by the color of some nodes, and the left hand of the parent node completes the operation.

Recently these two articles wrote for a long time, but by writing this, is basically mastered the main reason and operation of red and black trees, but also feel that the red and black tree is not so difficult to master, hope that through this way, master more common algorithms.

  

Algorithm--Introduction of red and black Tree Implementation (II.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.