Insert a roaming red/black tree

Source: Internet
Author: User

1. Introduction to the red/black tree

2. Introduction to the properties of the red/black tree

3. roaming the red and black trees

4. My EasyCoding Library

5. Download references and code

<1>. Introduction to the red/black tree  

The red-black tree is a balanced binary search tree, which is a common data structure in computer science. The most typical application is to achieve data association, such as map and other data structures. In, he first invented Rochelle bell, but he called it the "symmetric Binary Tree". what he called the "red and black tree" was in Leo J. guibas and Robert Sedgewick started with a paper. In this case, the red and black trees have existed for nearly 30 years. Today, they still have headaches for beginners.

<2>. Description

The red/black tree expands the Binary Search Tree and adds a Color attribute to each node. Each node must be red or black. In addition, to achieve the tree balance, the following restrictions are added ("restrictions" are used below ):

1. the node must be red or black.

2. The root node is black. If it is not black, the new node cannot be inserted according to the following type 4:

3. All the leaf nodes are black. Here, you can add the Sentinel element. As a leaf node, the node is black, which means the condition must be met.

4. The two subnodes of each Red node are black, that is, they cannot exist. The parent and child nodes are all red.

5. The number of black nodes on all simple paths from any node to each leaf node is the same.

These constraints guarantee a balance in the tree, which also determines that the insert, delete, query, and other operations on the red/black tree are relatively fast.

<3>. roaming the red/black tree  

Many beginners always first look at others' ideas (such as introduction to algorithms) when learning the red and black trees, and then basically get stuck, let's just calm down and think about what to do if I want to implement it? Okay. Are you ready to start roaming the red and black trees? Here we will not only list the situations in which insert operations are classified, but more importantly, what is the category?

Okay, now we have nothing to do. Suppose this is the first time we insert a node. To satisfy the first five of the above attributes, we obviously only need a few operations:

Generate a new node and copy data;

The color of the node is black;

Only one node tree is generated through the above operation, meeting the requirements of 1-5 properties. Obviously, this tree is a red-black tree.

 

After special circumstances are considered, let's assume that the node is added again. The first problem we face is whether the newly added node is marked as red or black? Obviously, whether the newly inserted node is black or red, the red/black tree limit 1, 2, and 3 must be satisfied. If the newly inserted node is identified as black, it may violate 5, however, if the newly inserted node is marked in red, it may violate 4. It seems that two nodes are similar.

However, consider this situation: if the newly inserted node is marked red and the parent node of the newly inserted node is black, it violates the Nature 4, that is to say, you do not need to re-adjust the red and black trees.

 

But if it is marked as black, it will definitely violate the nature 5. Okay, let's identify the inserted node as red, at least if we're lucky, you do not need to re-adjust the red and black trees.

After the color of the newly inserted node is determined, the specific insert operation is now started. Because the red/black tree is actually a binary search tree, then the newly inserted vertex must be at the lowest end of the Red-black tree. We ignore the process of searching nodes. Here, we only care about how to adjust the red-black tree after inserting nodes. Common Mathematical Methods: Classification Discussion

Case 1. If the inserted node is the root node, that is to say, the initial red/black tree is empty, This is the simplest case. Simply mark the node as black.

Void insert_case1 (struct node * n)
{

If (n-> parent = NULL)
N-> color = BLACK;
Else
Insert_case2 (n );
}

Case 2. If the newly inserted node is not the root node of the Red-black tree and the parent node of the newly inserted node is black, the red-black tree does not need to be adjusted.

 

Code:

Void insert_case2 (struct node * n)
{
If (n-> parent-> color = BLACK)
Return;/* Tree is still valid */
Else
Insert_case3 (n );}

Case 3. If the parent node of the newly inserted node is red, it is clear that the parent node and the child node cannot be red at the same time in the red/black tree ,.

 

Therefore, we need to adjust how to separate two adjacent red nodes without violating the red/black tree nature (or adjustable, obviously, the final result is that we need to change the parent node of the newly inserted node to Black (the newly inserted node is adjusted by the method to split the two red nodes, unless the node is identified as black, but this increases the black height). However, if the parent node is changed to black, it will violate the nature of the number of black vertices, direct modification is not feasible. can we achieve this by exchanging two nodes?

Obviously, the grandfather node of the newly inserted node must be black. Can it be achieved by exchanging the red and black nature of the parent node and the grandfather node? Apparently, this may violate the red/black tree nature of the newly inserted Uncle Tree. But if the uncle node is red, the problem may seem quite simple.

 

We only need to change the primary parent node to red, and change the parent node and Uncle node to black.

 

However, this introduces a new problem. Obviously, after G nodes are marked red, the parent nodes of G nodes and G nodes may be in violation of the red/black nature. To solve this problem, the tail recursion is used to adjust the node G.

Void insert_case3 (struct node * n)
{
Struct node * u = uncle (n), * g;
 
If (u! = NULL) & (u-> color = RED )){
N-> parent-> color = BLACK;
U-> color = BLACK;
G = grandparent (n );
G-> color = RED;
Insert_case1 (g );
} Else {
Insert_case4 (n );
}

}

One case has been solved. The following will be a more arduous task. If the uncle node is black, what should I do?

Case 4: Let's see if this is the case. P is red, U is black, and G is black. How can this problem be solved? By the way, do you forget our ultimate goal?

How to separate two adjacent red nodes without violating the red/black tree nature (or adjustable.

 

 

Directly change the P node to Black is not acceptable, this will increase the G-P-U path on the black height, no idea, OK, to look back at case 3, after all, a problem has been solved. In case 3, we changed the color of node G. Why can we modify it? Obviously, G is the most vertex (the highest generation) node, the color of the vertex node can be red (re-adjusted) or black.

What if we raise the P node to the current G position (through the rotation of the tree )?

 

Now we can mark P color as black, but it will damage the black path of the P-G-U, use the exchange of ideas, the exchange of P and G color can be.

Now we have basically solved the problem that if Uncle is black in the red/black tree, the rest of the work is to analyze the rotation direction, and rotate the node P and N based on whether the left or the right.

This is case 4:

 

Or:

 

Void insert_case4 (struct node * n)
{
Struct node * g = grandparent (n );
 
If (n = n-> parent-> right) & (n-> parent = g-> left )){
Rotate_left (n-> parent );
N = n-> left;
} Else if (n = n-> parent-> left) & (n-> parent = g-> right )){
Rotate_right (n-> parent );
N = n-> right;
}
Insert_case5 (n );}

In this way, the scenario where P and U are no longer in the same straight line is converted into a uniform straight line. case 5 we will handle the situation in the same straight line:

Case 5:

 

Or:

 

Void insert_case5 (struct node * n)
{
Struct node * g = grandparent (n );
 
N-> parent-> color = BLACK;
G-> color = RED;
If (n = n-> parent-> left) & (n-> parent = g-> left )){
Rotate_right (g );
} Else {/* (n = n-> parent-> right) and (n-> parent = g-> right )*/
Rotate_left (g );
}

}

The analysis of all the situations inserted by the red and black trees is complete. That is to say, is our classification discussion complete?

 

Okay, it seems that we have exhausted all the inserted information of the red and black trees. Here is an animated demonstration of the applet, which is very vivid.

<4>. My EasyCoding Library 

Finally, let's talk about a library that is being developed based on the c # Language algorithm. It is under development and there are still many technical difficulties (for cainiao like me ), I named this project EasyCoding. The basic project structure is as follows:

 

Collections mainly implements some data structures. Now we have completed Bag, Association, BinarySearchTree, HashList, Heap, PriorityQueue, VisitableHashtable,

VisitableLinkedList

, VisitableList, VisitableQueue, and VisitableStack.. net collection class re-encapsulation. For example, if the Visitable-XXX collection class is used internally. but the visitor mode is re-implemented (mainly for the expansion of the functions of the Collection class). Below is a piece of code in the Test project, demonstrate how to use the visitor mode to Expand functions of the Collection class: [Test]
Public void TestVisitor ()
{
VisitableStack <int> stack = new VisitableStack <int> ();
Stack. Push (2 );
Stack. Push (4 );
Stack. Push (9 );
Stack. Push (3 );

ComparableFindingVisitor <int> visitor = new ComparableFindingVisitor <int> (9 );
Stack. Accept (visitor );

Assert. AreEqual (visitor. Found, true );

Visitor = new ComparableFindingVisitor <int> (5 );
Stack. Accept (visitor );
Assert. AreEqual (visitor. Found, false );
}

Next, we plan to implement some complex data structures, such as the red and black trees, avl trees, jump tables, FibonacciHeap, and top-layer storage containers of graphs.

Algorithm is mainly used to implement the Algorithm library. It has completed some simple sorting algorithms and intends to add some common search algorithms and graph theory algorithms;

The Test project uses the unuit Test framework to Test Collection and Algorithm;

Visualization is mainly intended to achieve visualized operation of data structures and algorithms. It is not yet started (not technically skilled) and is intended to be implemented using silverllght.

 

The road is long and the distance is long. Continue.

<5>. Download reference materials and code  Http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx

Http://libredblack.sourceforge.net/

Red/black tree dynamic demonstration: http://secs.ceas.uc.edu /~ Franco/C321/html/RedBlack/redblack.html

Http://gauss.ececs.uc.edu/RedBlackTester/redblack.html

Http://www.cs.auckland.ac.nz /~ Jmor159/PLDS210/red_black.html

Http://www.cs.auckland.ac.nz /~ Jmor159/PLDS210/red_black_op.html

Http://zh.wikipedia.org/wiki/%E7%BA%A2%E9%BB%91%E6%A0%91

Http://blog.csdn.net/v_JULY_v/archive/2010/12/29/6105630.aspx

Http://en.wikipedia.org/wiki/Red-black_tree#Operations

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.