Introduction to Algorithmic Learning-red-black TREE

Source: Internet
Author: User

1. Red and black tree (Red-black trees) Introduction:

The Red-black tree (RBT) can be said to be a non-strict balanced version of the Binary-search tree. Correspondingly, the Balanced binary tree (Balanced binary trees) is also called the AVL tree (because it is g.m. The tree Adelson-velsky and E.M Landis invented in 1962 is a strictly balanced version of Binary-search tree.

BST achieves the most balanced state known as AVL. The maximum height difference for the two son subtree of any node in the AVL tree is one, and find, insert, and delete are O (LG N) on average and worst case. But because adding and removing nodes can break the "balance state," in most cases it is necessary to rebalance the tree through multiple tree rotations. So simply put, if your application is far more than the number of additions and deletions, then AVL is the best, but if the number of additions and the number of lookups, RBT because compared to AVL does not have too much rotation, efficiency is higher than AVL. And in the actual situation, the application of RBT is also more extensive. At least the book "Intro to Algo" is mainly about RBT.

2. Several basic properties of the red and black tree:

because RBT is a non-strict balanced version of Binary-search tree, the red-black tree inherits the basic properties of BST: The key value, and the basic nature: for any node x in the tree, there are x.left.key<x.key<= X.right.key. In addition, the leaf node of BST is not called the leaf node in RBT, the leaf node of RBT is nil, so the Father node of the root node of BST is no longer empty in the RBT representation, but nil or called Tree.sentinel. The leaf nodes in BST are the same, and they have children as nil nodes. Next comes the unique properties of RBT: color, which is that each tree node has its own color, either red or black .

Then there are five basic properties of the RBT: 1) Each tree node is either red or black; 2) the root node must be black; 3) nil node is black; 4) If a node is red, its child nodes are black (except for nil nodes). No two contiguous red nodes can be found on all paths from each leaf to the root, 5) All paths from any node to each of its leaves contain the same number of black nodes. as shown in the following:

  

3. Rotation:

Because the nature of the RBT may be changed after performing an operation or a delete operation. So in order to maintain the basic properties of the RBT [2], we need to change the color of the nodes of some trees and change the structure of the tree. Shows the rotation action of the tree:

          

There are two types of rotational actions: Left and right. The left-rotation is counterclockwise, and the right-rotation rotates clockwise. Take Left-roation as an example, as shown on the right,

First step: establish the "parent-child relationship" of Y's left children beta and x: Β.parent=x and x.right=β.

Step Two:y replaces x:(when x is not the root node) y.parent=x.parent and (x.parent.left==x)? (y=x.parent.left): (y=x.parent.right).

(When x is the ROOT node) y=root

Step Three: reverse the X, y parent-child relationship: X=y.left and x.parent=y;

1left-ROTATE (T, x)2y=X.right3x.right=Y.left4 ifY.left! =T.nil5y.left.p=x6Y.parent=x.parent7 ifx.parent==T.nil8t.root=y9 Else ifx==X.parent.leftTenx.parent.left=y One Elsex.parent.left=y Ay.left=x -X.parent=y

4. Insert:

The insertion of red and black trees is basically similar to BST. It is not clear that the BST insertion algorithm can refer to my blog: http://www.cnblogs.com/fu11211129/p/4214047.html

The insertion of the red-black tree makes some fine-tuning on the BST insert, which compares the two inserted pseudo-code shows.

Tree-insert (T, z)//bst insertion algorithm 1 y=nil2 x=t.root3 while (x!=nil) 4 y=x5 if (Z.key<x.key) 6 x=x.left7 else X=x.right8 Z . P=y9 if (y==nil) t.root=z10 else if (z.key<y.key) Y.left=z11 else y.right=z
Rb-tree-insert (T, z)//RBT insertion algorithm 1 y=t.nil2 x=t.root3 while (x!=t.nil) 4 y=x5 if (Z.key<x.key) 6 x=x.left7 Else X=X.R Ight8 Z.p=y9 if (y==t.nil) t.root=z10 else if (z.key<y.key) Y.left=z11 else y.right=z12 z.left=t.nil13 z.right=t.nil14 Z . Color=red17 Rb-insert-fixup (T, z)

Comparing the two insertion algorithms, we can note that four different, 1) The nil in BST is replaced by T.nil, because nil is considered a node in the red and black tree system. 2) Rbt-insert algorithm in 14-15 rows, we will t.nil respectively assigned to Z.left and Z.right, is to maintain the reasonable structure of the tree. 3) in the Rbt-insert algorithm, the color of the z is set to red in the 16 row. 4) because the underlying properties of the red and black trees may be destroyed after the coloring of Z, we call the Rb-insert-fixup function (described below) to show Gu rbt tree so that it can still maintain its basic properties.

5. Insert repair (metaphor for the ancient samurai social structure in Japan):

The largest of the small Japanese samurai is called General, in possession of many names, the name is a city has a territory, there are soldiers have the banner, there are many family officials for its service. The minister also divided many grades, the name of the site part to the family minister, this is the city master. Every family minister can have his own family minister, as long as your site's income salary affordable. This hierarchical system, very strict, no birth guarantee, even if the credit can not climb up. For in addition to the general, the samurai must be loyal to one of the Lord's, the name is also the general's family minister. And this allegiance is inherited, and your children and grandchildren will be loyal to the Lord's descendants.

The situation in Japan and China is different, no one dares to shout out the king, rather have a kind of. So Toyotomi Hideyoshi can start from the bottom of the ordinary samurai, step by step to achieve Guan Bai (and general level, then no general, equivalent to the general), became an incredible legend. When the treatment with your credit or ability is more than the Lord can give, it can happen Hiddink, or even subvert the Lord's things. It is said that the Japanese Warring States period is a time of the next gram.

Well, it's a little bit far away, get back to the chase. We put the red black tree Two color nodes, representing two basic samurai types, black for the integrity of the machine has been loyal, but at the same time also mediocre inaction incapable. Red means both talent and ambition.

Insert operation, as if a new samurai, no background, no exploits. But he is capable and ambitious ( red ), just like Toyotomi Hideyoshi. If with a black type of the Lord, although eventually will not be reconciled to the people under, but there is no condition "on the next gram", because this master of the Great Lord (Lord of the Lord) loyal, conscientious, you can also upsets, only Pating. This situation corresponds to the RBT structure has stabilized.

But if the Lord is Red (ambitious), then the new samurai will have a fantasy, all day with the great lord to make a small report, said he was treason. Anyway, my Lord's loyalty is limited, there are many handles, but the Lord does not have that insight. The great Lord saw some false evidence, the treason of this matter rather than the vertical. So the new samurai reported active, but the Lord became his own family minister (such as the second state). But the foolish Lord will soon pay the price and become the next target of the new samurai (such as the third State).

            

(b = new Samurai, a means the Lord of B)

Another situation is that the Lord's ambition, but the other ministers of the great lord if there is ambition, the situation is not the same, if the other family minister also has the ability, then the lively, this one from the two tiger dispute, not peace (here omit tens of thousands of words). The ability of the Lord is mediocre, unable to control, and eventually become a big mess, after a bloody, the big master of the public has appeared a laureate Wei home, calm the civil strife, the original two strong home owners were all wiped out, home owners replaced by loyal and reliable (black) people . And The Big Master's new home, ambition began to swell ( turn red ).

Go through the complete process below:

Well, starting with a, the new samurai is numbered 4 (I'm not going to mark the red circle here, the Shadow is red) and I work at the hands of my 5. Family Minister 5 not willing to take the next person, and 4 found this, 4 want to Cuanduo 5 to usurper. Unfortunately, the same 7 of the family minister, 8, is also ambitious ( red ). So under the rule of the name 7, there was a chaotic situation, four ... The final name of the family has a new name 7, to quell the civil strife, the family Minister 5 and 8 for their loyal family minister. And at the same time, the new name 7 is also a swell of ambition ( turn red ). (On the way corresponds to state 1 after Case1 reached state 2)

The new name 7 ambitious, and his Lord 2 is also ambitious, so the name 7 can only fight and play Yin, the name 7 to the great Lord 11 said the Lord 2 bad. The Great Lord is also two goods ( black ), listen to the wind is rain, name 7 reported active, so that the Lord 2 became a name 7 subordinate. But soon, the two goods hit 11 also to self-food consequences, name 7 directly accounted for his position.

6. Porting:

because the porting operation is a basic action of the delete operation, here is a brief explanation. RBT's transplant algorithm is basically consistent with BST, you can refer to the blog: http://www.cnblogs.com/fu11211129/p/4214047.html

Rb-tranplant (T, U, v) 1 if (U.parent==nil) T.root=v2 else if (u==u.parent;. left) U.parent.left=v3 Else u.parent.right=v4 v.parent=u.parent

We can see that only the fourth line is different, the reason is very simple, rbt the nil as a node.

7. Delete:

The delete operation is a bit of a hassle, but similarly, the BST delete operation is similar, http://www.cnblogs.com/fu11211129/p/4214047.html

The following is a pseudo-code that RBT the delete operation:

Rb-delete (T, z)   The total operation of simply deleting a node 1 if left[z] = nil[t] or right[z] = nil[t] 2 then    y←z 3    else Y←tree-successor (z  ) 4 if LEFT[Y]≠NIL[T] 5 then    X←left[y] 6    else X←right[y] 7 P[x]←p[y] 8 if p[y] = nil[t] 9 then    Root[t] ←x10    else if y = left[p[y]]11 then            left[p[y]]←x12            Else right[p[y]]←x13 if Y≠z14 then    key[z]←key[ y]15         copy y ' s satellite data into z16 if color[y] = BLACK17 then    rb-delete-fixup (T, X)

Because compared to the BST delete algorithm, is to add some node color processing mechanism, so here no longer repeat. After we understand the deletion of BST, RBT is almost there.

8. Remove the fix (not yet think of the appropriate metaphor, thinking that it will update this section):

Stick to the pseudocode first, and then combine the code to do an analysis:

Rb-delete-fixup (T, x) restore with the work of keeping the red-black nature 1 while x≠root[t] and color[x] = BLACK 2 does if x = Left[p[x]] 3 Then  W←RIGHT[P[X]] 4 if color[w] = RED 5 then color[w]←black?  Case 1 6 color[p[x]]←red?  Case 1 7 left-rotate (T, p[x])?  Case 1 8 w←right[p[x]]?                          Case 1 9 if color[left[w] [BLACK and color[right[w]] = BLACK10 then color[w]←red  ?  Case 211 x p[x]?          Case 212 else if color[right[w]] = BLACK13 then Color[left[w]]←black  ?  Case 314 color[w]←red?  Case 315 Right-rotate (T, W)?                            Case 316    W←RIGHT[P[X]]?  Case 317 Color[w]←color[p[x]]?  Case 418 Color[p[x]]←black?  Case 419 Color[right[w]]←black?  Case 420 left-rotate (T, p[x])?  Case 421 X←root[t]? Case 422 Else (same as then clause with "right" and "left" exchanged) Color[x]←black

Earlier, I have said , because after inserting, or deleting the node, may violate, or destroy the original nature of the red and black tree, so in order to make the insertion, or delete the node after the tree remains a new red black tree, it should do two aspects of work: 1, part of the color, re-coloring 2, Adjust the direction of part of the pointer, that is, left and right rotation. And the following all the text, is for the red black tree to delete the node after the work done to repair the nature of the red and black tree.

Case 1: The sibling node of the current node is red; The solution is left-handed on the parent node of the current node, ending. At this time the red and black tree nature all restored.


Scenario 2: The sibling node of the current node is black and the child node of the sibling node is also black solution: Just turn the sibling node into red on the line.

Case 3: The sibling node of the current node is black, and the left child of the sibling node is red and the right child is black. Solution: Turn right on the left child of the sibling node and swap the color of the father's left child.

Case 3: The sibling node of the current node is black, and all two children of the sibling node are red. Solution: Turn left on Father node, and swap father right child color.

(Japanese samurai version Explanation: In the introduction of the insertion, we "insert the story" of the "master" is a new debut of the Samurai, delusions, lupin carring ... , here we "delete the story" of the Master is a "to retire" Samurai X, but adhering to the samurai "wretched" characteristics, X laid off before, always to the pattern of chaos to teach. But because X is "retired", he is incapable of himself (black). So he shifted his gaze to his brother, but it depends on what his brother W is.

If he unambitious, then x lifts brother W's ambition ( turn red ) (corresponds to CASE2).

If his brother W is ambitious ( red ), X will not be cuanduo, but the art of war has a cloud, outward must first Ann (I do not know is not in the art of war, let's say so), if W's two family officials are all right, so good, W can be assured to grab class seizure power (corresponding case1), W after success complacent, life degenerate ( turn black ), and by W Power's once superior B began to hardships ( red ) (corresponding case1).

If his brother W unambitious, but one of his family minister ambition is not small, then X will instead start Cuanduo W's insurrection (corresponding case3).

If his brother W unambitious, and sadly, his family minister did not really sink in his. So X thought I didn't have to save much, let them fight it, the last D family out a new W, first successful usurper, and then change their own men to the center of the person ( black )

 

Introduction to Algorithmic Learning-red-black TREE

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.