Introduction of algorithm---red-black tree implementation (I.)

Source: Internet
Author: User

I. Overview

Red-black tree is a classic storage structure, in itself is a binary search tree, just on this basis, the tree node added a property to represent the color (red or black). By restricting the coloring of nodes from the root node to the individual paths of the leaves, it is ensured that no path will exceed twice times the length of the other path, so that the red-black tree is nearly balanced.

The red and black trees have not been fully understood, always feel too difficult, daunting, recently determined to find out, but also spent a long time, but finally understand. Record it for a better understanding.

Ii. characteristics of red and black trees

As a red-black tree, you need to have these 5 restrictions, as follows:

1) Each node in the tree is either red or black

2) The root node of the tree must be black

3) The color of the leaf node (null node) is black

4) If a node is red, its son node must be black

5) The number of black nodes must be the same on all paths from a node to its descendant nodes

These 5 characteristics, can also be considered as constraints, is the necessary and sufficient conditions to determine whether the tree is a red-black tree. Seemingly unrelated, in fact, are in order to achieve the goal of controlling the length of the path set, to do a detailed explanation of these characteristics. Feature 1 will not explain.

A) the root node is black and the leaf node is black: This is also the agreement, of course, we can also be defined as must be red, in short, remember that Black is the main theme, red is used to play the role of spacing. In addition, the leaf node refers to the last layer node, the node does not include data, only represents the end of the path. In this way, all data nodes have two sons, possibly two data nodes, or one leaf node for a data node, or two leaf nodes. And the leaf node has no son, it is the last node of each path.

b) Properties 4 and 5 have recursion, and by these two properties, any subtree of the red-black tree has the characteristics of other red-black trees except the property 2, while the root has only one. So after this limit, for the tree adjustment brought convenience, due to the red node discontinuity and the number of black nodes limit, so that the length of any one or two path is not more than twice times. The worst two path difference is also twice times (that is, one path is full of black nodes, and the other path has a red-black interval)

Three, the rotation of the tree

The rotation of the tree is also a classic algorithm, not limited to the red and black trees, is to adjust the height and balance of the tree to do an adjustment. Divided into left and right, the logic of the two operations is the same, just the opposite direction, so we'll just introduce a spin.

When a node is left-handed, we have to assume that it is a right child with a non-leaf node, otherwise the rotation is meaningless, and in the right hand, we think it is the left child of the non-leaf node.

The following gives a left-handed direct:

, the main operation of the left-hand rotation for the B-node is as follows:

1) Set B's right child to E's left child, and the father of the child with E to leave is set to B

2) Set E's left child as the father of B,e, father of B, b father originally pointing to B's child node, pointing to E

3) The father of B is set to E

Let's look at the implementation of the Java code:

/*** Left-handed to node p, where we think P is the node B **/Private voidRotateleft (entry<k,v>p) {if(P! =NULL) {Entry<K,V> r = p.right;//R is B's right child, that is, E inP.right = R.left;//B's right child is set to E's left child, after operation, B's right child from E into F            if(R.left! =NULL) R.left.parent= P;//correspondence, the father of F changed from the original E to the BR.parent = p.parent;//The father of E changed from B to B.            if(P.parent = =NULL) Root= R;//B's father is not empty, so this step will not be executed            Else if(P.parent.left = =p) P.parent.left= R;//if B is his father's left child, then his father's left child points to E, and B is the left child, so walk this branch, A's left child becomes e            ElseP.parent.right= R;//B is the word of his father's right child walking this branchR.left = p;//Change E's left child (formerly F) to BP.parent = R;//Change the father of B (formerly a) to E        }    }

The right-hand side of the tree is similar, and is no longer explained here.

Iv. addition of red and black trees

The red and black tree itself is a binary search tree, meaning that the value of a node must not be less than the value of its left child, and not greater than the value of its right child. When a node is added, traversing from the root, it will be possible to find a suitable node to become the parent node of the current node, and the current node becomes the right child of the appropriate node, or the children of the right, depending on the size relationship between the values of the two nodes.

When adding a node to a known red-black tree, no matter what color the current node is, the nature of the red-black tree may be destroyed, so after the addition, there are some steps to adjust the tree to make it a red-black tree again.
So, adding a node mainly does these two things:

1) traverse from the root to find a suitable node as the parent node of the new element.

2) Adjust the tree to re-satisfy the nature of the red-black tree.

The following is a case where a new node 23 is added to an existing red-black tree, and a Purple line indicates a lookup path.

The lookup process is relatively simple, the code is not listed, followed by the second question, adjust.

When adding a new node, by convention, the color of the new node is red, and since we have to adjust, we have to figure out which properties might be destroyed after the addition of the Red section. Obviously, the new node satisfies the non-red or black nature, the leaf node is always black, and the path on the black node is not increased, so the nature of 1,3,5 will not be destroyed, 2,4 may be destroyed, the specific situation is:

A) When the original tree is empty tree, the new node is the root, the root can not be red, so the nature of 2 is destroyed, this situation is relatively good processing, directly to the node color black.

b) When the Father node is red, the parent-child node is red, the nature of 4 is destroyed, the above figure is the effect. In this case, handling can be a bit cumbersome. The following is a main introduction to this situation.

Since the nature of 4 is destroyed, we have to restore the nature of 4, the restoration of the method only to black the parent node, but this will introduce a new problem, that is, the parent node path of the number of black nodes than the other paths more than 1, then need to continue processing, but we have the problem back to the first layer, so that the root node The solution must be found, and that is the process of core thinking .

It needs to be clear that if the Father node is red, there must be a grandfather node, and its color is black. According to the color of its Uncle node and the location of the new node, can be divided into the following three kinds of situations:

A) Uncle node is red, this situation, regardless of the current node position (left son or right son is not affected)

In this case, in addition to the parent node, we can turn the Uncle node black together, but so the Uncle node and Father node path in the black node is 1 more than the other path, so we continue to turn the grandfather node red. After this operation, the number of black nodes of the two paths from the grandfather node has not changed, then its two subtrees are already red-black trees.

But after the grandfather node turns red, if grandfather's father is also red, it still destroys the nature 4, so we need to keep the grandfather node as the new current node to be processed by the algorithm.

The situation of the change is handled as follows:

b) Uncle node is black and the current node is the right child of the Father node.

This situation, as shown, because the Uncle node is already black, so can not be processed in a way, so that if the grandfather node to turn red, then the Uncle node is located in the path of the number of black nodes will be less than 1, do not meet the red black tree.

But the parent node is going to be black, so that the indirect explanation of the grandfather node or to turn red, in order to achieve this goal, does not affect the Uncle node, there is a perfect solution, is rotation. In, the grandfather node as the fulcrum of the right-hand, so that the Father node up, the grandfather node becomes the child node of the Father node, so that the Father node can be black, grandfather node red, Uncle node on the path of the number of black nodes, the total number has not changed.

This idea is possible, but in the case of direct this is problematic, according to the right-hand algorithm, grandfather node 25 will be red, and become the parent node of the current node 22.5, as a result, the parent-child node is the same as red. So you can't rotate directly.

But we can see that the two child nodes of node 22.5 are black, so assuming that node 22.5 is in the 22 position, there is no such problem.

So, this situation we have to do one more step, that is, its parent node 22 as the fulcrum for the left rotation, because the Fulcrum node and its right child are red, so the number of black nodes will not be changed.

The diagram for this process is as follows:

It is necessary to make sure that the current node points to the original parent node, so that the current node and its parent node is red, in order to continue processing, otherwise, it becomes the current node and its child nodes are red, unable to continue recursion.

Through this rotation, the current node is successfully the case of the right child of the parent node, converted to the situation where the current node is the parent node of the left child.

c) The Uncle node is black and the current node is the left child of the Father node.

If the situation 2 figure out, then this situation is better understood, that is, by right-hand on the grandfather node, so that the father of the node move up, then the father turned black, grandfather turned red, because the original father's right child is black, so, the grandfather node red, the left child is black, will not destroy the nature of the 5. Examples are as follows:

  

At this point, the whole tree is restored to the characteristics of the red and black trees.

It should be explained that the above scenario 2 and 3, are described in the context of the parent of the current node for the grandfather's left child, when the parent node is the right child of the grandfather, its processing is actually symmetrical, here is no longer an example. In addition, the situation 2 will certainly turn into the situation 3, just the middle more a left-handed operation.

Finally, the root node is always set to black.

If all of the above can be understood, then the implementation of any one language including pseudo-code will be easy to understand, the following Java version of the processing code, do not do a detailed analysis, only to illustrate the code description of the process described in the form.

Private voidFixafterinsertion (entry<k,v>x) {X.color= RED;//new node is red         while(X! =NULL&& x! = Root && X.parent.color = =RED) {            if(Parentof (x) = =Leftof (Parentof (Parentof (x))) {Entry<K,V> y = rightof (Parentof (Parentof (x)));//Uncle Node                if(Colorof (y) = =RED) {                    //Uncle node for the Red caseSetColor (Parentof (x), BLACK);                    SetColor (y, BLACK);                    SetColor (Parentof (Parentof (x)), RED); X=Parentof (Parentof (x)); } Else {                    //for the case of black//x is the right subtree, one more left rotation, and finally the right rotation.                    if(x = =Rightof (Parentof (x))) {x=parentof (x);                    Rotateleft (x);                    } setcolor (Parentof (x), BLACK);                    SetColor (Parentof (Parentof (x)), RED);                Rotateright (Parentof (Parentof (x))); }            } Else {                //the father of the current node is the right child, operation symmetryEntry<k,v> y =Leftof (Parentof (Parentof (x))); if(Colorof (y) = =RED)                    {SetColor (Parentof (x), BLACK);                    SetColor (y, BLACK);                    SetColor (Parentof (Parentof (x)), RED); X=Parentof (Parentof (x)); } Else {                    if(x = =Leftof (Parentof (x))) {x=parentof (x);                    Rotateright (x);                    } setcolor (Parentof (x), BLACK);                    SetColor (Parentof (Parentof (x)), RED);                Rotateleft (Parentof (Parentof (x))); } }} Root.color=BLACK; }

V. Summary

The addition of red and black trees is relatively simple, because the new nodes are red nodes, so the crux of the problem is that when the parent node of the new node is red, how to eliminate the problem of two consecutive red nodes.

The main idea to solve the problem is to find a way to darken the parent node and achieve the purpose of the subtree as a red-black tree, which goes back to the root node.

Introduction of algorithm---red-black tree implementation (I.)

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.