The red and black trees belong to the balanced binary tree, so many operations are the same as the root binary tree. To learn the red and black trees, we must first understand the two-fork tree, and can be implemented in code.
I mainly talk about how I write a red and black tree, not to do a very fine explanation. We mainly learn to rotate, insert, delete. Other operations The root binary tree is the same.
Rotation and insert operation, I am with the STL source analysis, the book is very clear, a morning can understand + realize, then the afternoon to learn to delete the operation, hehe ... Deletion is not described in the book, I am a control algorithm in the introduction of pseudo-code in line with the code for the study. However, some of the source code in the blog is wrong, it is recommended that you first glue down his codes, and then run maturity, to determine that no problem with his code to learn.
Then the rotation operation, the rotation operation is the transformation element position, has reached the goal of balance.
Left-hand operation, this is not difficult, the basic understanding of the process can write code, it is important to note that if 1 is the root node, after the rotation of the 7 is set to the root node.
//L -//1. Set X's right child to Y's left child (if Y has left child, set the left child's father to X)//2. Set Y's father as the father of X, and set X's father's child to Y (depending on the case of X, consider whether the child is the root node)//3. Set X's father to Y to set Y's left child to xStatic voidLeft_rotate (Node * x, Tree *tree) {Node* y;//y is the right child of Xy= x->Right ; X->right = y->Left ; if(Y->left! =nil) y->left->parent =x; Y->parent = x->parent; if(Tree->root! =x) {if(x = = X->parent->Left ) x->parent->left =y; Elsex->parent->right =y; } ElseTree->root =y; Y->left =x; X->parent =y;}
You can implement the code according to your own understanding. Note that the left hand, the rotation point must have the child.
The right-hand side is the same as the left-side operation. No introduction is made here.
There is also an operation called Double-spin, which is done by left-hand and right-handed. Here is a brief introduction.
The first step is to rotate the point by 5 and left.
The second step is to rotate the point by 10 and turn right.
Red black Tree (a) rotation