Insertion and deletion of red and black trees

Source: Internet
Author: User

Red black Tree is a self-balancing binary search tree. Red and black trees are similar to AVL trees in that they maintain the balance of binary lookup trees with specific actions when inserting and deleting operations, resulting in higher lookup performance. Red-black trees can be searched, inserted, and deleted within O (log n) time.
Binary search tree can see binary search tree
AVL tree can see the insertion and deletion of AVL tree
1. Nature of red and black trees

The self-balance of the red-black tree depends on its properties:

Nature 1. The knot is red or black. Nature 2. RootKnot Pointis black. Nature 3. EachKnot PointNode (NILKnot PointEmptyKnot Point, unlike the other two-fork search trees, the red-black tree connects the children of the leaf nodes to the nil node to simplify the boundary conditions) is black. Nature 4. Each redKnot PointThe two childKnot PointIt's All Black. (no two consecutive red on all paths from each leaf to the rootKnot Point) Property 5. From any oneKnot PointAll paths to each of its leaf nodes contain the same number of black nodes.

Here is a definition, a node to its leaf node on the path of the number of black nodes, called the node's black height, according to the nature of 5 can be known, a node of the Saozi right subtree of the black height should be the same.
According to the nature of 5, we can also know the balance of the red and black Tree: A node of the left and right two sub-tree height difference is one times. In extreme cases, a subtree A is all black nodes, the other subtree B is red and black, because their black height is the same, so the red node in B is the same as the number of black nodes, so B is twice times the height of a.

A red and black tree as shown.

All "leaf nodes" of the red and black tree point to the same nil sentinel node, the Nil sentinel node is a member variable of the red and black tree T, at this time these "leaf knot" is no longer the leaf knot point, so they can make black can also be red, Sentinel Nil knot point must be black. In addition, the parent node of t.root, the root node of the red and black tree, also points to the Sentinel nil node. We just need to remember that the nil node is just a boundary condition for simplifying the balance of the tree after insertion and deletion, and has no effect on the nature of the tree itself. This is reflected in the following algorithm introduction and in the sample code.

First, the rotation of the program, which is the same as the rotation of the AVL tree, but do not need to adjust the height of the node.

void Leftrotate (Tree *tree, node *x) {Node *y = X->right;x->right = Y->left;if (y->left! = Tree->nil && y ->left = NULL) {y->left->parent = x;} Y->parent = x->parent;if (x->parent = = Tree->nil | | x->parent = NULL) {tree->root = y;} else if (x = = x->parent->left) {x->parent->left = y;} Else{x->parent->right = y;} Y->left = X;x->parent = y;} void Rightrotate (Tree *tree, node *x) {Node *y = X->left;x->left = Y->right;if (y->right! = Tree->nil && Amp Y->right = NULL) {y->right->parent = x;} Y->parent = x->parent;if (x->parent = = Tree->nil | | x->parent = NULL) {tree->root = y;} else if (x = = x->parent->left) {x->parent->left = y;} Else{x->parent->right = y;} Y->right = X;x->parent = y;} 
The code above is the operation of the left and right rotation of the node x in the tree. The rotation operation is essentially a modification of the pointer to the operation, so it can be completed in constant time.

2. Insertion of red and black trees

Like the AVL tree, after inserting and deleting nodes, the red and black trees are rotated to adjust the balance of the tree. The red-black tree inserts the node z in the same way as the normal binary search tree, inserting the new node z as a leaf node into the bottom of the tree. The difference is that the red black tree points the new node z as a red node, pointing its child pointer at the nil node, and then, when the parent node of the new node z is red, it needs to be adjusted (if the parent node of the new node z is black, it will not violate any nature, especially since z is red, So will not violate the nature of 5, that is, black high unchanged).

The design of the red-black tree adjustment algorithm follows one principle: red-black trees can only violate at most one point at a time.

There are 3 cases where the red-black tree is adjusted after inserting a junction Z.

Situation 1. The tertiary node y of z is red.

The new node inserted in the left image Z is a red node, its parent node A is red, violates the nature of 4, so it needs to be adjusted (because the node A is red, according to the nature of 4, because the tree itself is balanced, so the node C must be black). Because its tertiary node y is red, so you can modify the node A, Node B is black, when the node C of the black High will change, from the original 0 (ignoring the subtree A, B, R, D, E of the black height) into 1, so you also need to change the node C to red to maintain its black height unchanged. At this point, because the node C is changed from black to red, if the node C is the parent node is red, then it will violate the nature of 4, so node C becomes a new node Z, from here to start back to adjust the tree.

This is consistent with the case where the newly inserted node z is the left subtree of Node A.

For the newly inserted node z is the junction of the right subtree of node C with the above symmetry.

Scenario 1 is a relatively simple situation.

Situation 2. Z's tertiary node y is red and z is a right child

Situation 2 can not be as in case 1 by modifying the color of the parent node of Z to maintain the property 4, because if the parent node of z becomes black, then the tree will change the black, will inevitably cause a violation of the nature of 5. In the case of Figure 1 above, assuming that the node Y is black, then the right subtree of node C is 1 (ignoring subtree D and e), Gow is the same, if the simple modification Node A is black, then the left subtree of node C will be 1 larger than the right subtree, which will not help even if the node C is changed to red.

This can be done by turning the parent node of node Z to turn case 2 into case 3.

Situation 3. Z's tertiary node y is red and z is a left child.

Situation 2 turns into situation 3 and then the process of processing for situation 3 can be seen.

Situation 2 by the Node A to a left rotation into the case 3, when the node z is no longer the original B, but the node A, when the tree is still only a violation of the nature of 4. Situation 3 by a right-hand node C, and then change the Node B and node C color, get to the right.

First to prove the correctness of this operation:

For the left, due to the first insertion of the node z, only violated the nature of 4, the nature of 5 is still satisfied, assuming that the black height of sub-tree a ha, subtree B of the black high for HB, and so on, can know hb==hr==ha==hd,hc=hd+1, on the node a left to turn into the case 3, that is, when the figure, The tree still only violates the nature 4, the new node z is the Node A, then the node C right-click and modify the color to get to the right, at which point A and node C are balanced, Node B is balanced, and Node B's black height is hd+1. So, the whole operation, the black height of the tree is unchanged, and satisfies all the properties of the red-black tree.

During the red-black tree adjustment process, Z always points to a red node, so z never affects the black height of the tree in which it is located, so we always focus on whether the parent node of node z is red, and if so, it means that it violates the nature of 4 and needs to be adjusted, otherwise it can exit the loop. At the end of the algorithm, we also need to pay attention to the nature of 2, the root node of the color to black, the root node color changes will definitely not cause the tree imbalance, and change it to black will not cause a violation of the nature of 4.

Here is the definition of red and black trees and their nodes.

typedef struct NODE{INT value;int color;//node color struct node *parent;struct node *left;struct node *right;} node;typedef struct Tree{node *root; Node *nil;//Sentinel} Tree;

The following is a C implementation of the red-black tree inserted program:

void Insertrbtree (tree *tree, int value) {if (Tree->root = = NULL) {tree->root = Createrbnode (tree, value); Rbinsertfixup (tree, tree->root); return;} Node *node = Createrbnode (tree, value); Node *n = tree->root;while (1) {if (value < N->value) {if (N->left = = Tree->nil) {n->left = Node;node->p arent = N;break;} n = n->left;} Else{if (N->right = = Tree->nil) {n->right = Node;node->parent = N;break;} n = n->right;}} Rbinsertfixup (tree, node);}
In general, the program is similar to a generic binary search tree, except that it requires the Rbinsertfixup method to be adjusted for the newly inserted node node when the insert is complete.

void Rbinsertfixup (Tree *tree, Node *z) {while (Z->parent->color = = RED) {if (z->parent = = z->parent-> Parent->left) {Node *y = z->parent->parent->right;if (Y->color = = RED) {//Case 1z->parent->color = Black;y->color = Black;z->parent->parent->color = Red;z = z->parent->parent;} Else{if (z = = z->parent->right) {//Case 2z = z->parent;leftrotate (tree, z);} Case 3z->parent->color = Black;z->parent->parent->color = Red;rightrotate (tree, z->parent-> parent);}} else if (z->parent = = z->parent->parent->right) {//with the above symmetric node *y = z->parent->parent->left;if (y >color = = RED) {Z->parent->color = Black;y->color = Black;z->parent->parent->color = RED;z = z-> Parent->parent;} Else{if (z = = z->parent->left) {z = z->parent;rightrotate (tree, z);} Z->parent->color = Black;z->parent->parent->color = Red;leftrotate (tree, Z->parent->parent);}}} Tree->root->color = BLACK;} 
The Rbinsertfixup method loops through whether the parent node of node z is red, or if not, exits the loop. When node Z points to the root node, the zero node is black and therefore exits the loop because the parent node pointer to the root node points to the nil node. This is the specific embodiment of the above-mentioned "set nil node simplification boundary problem".

3. Removal of red and black trees

The red and black trees need to be adjusted only when the black nodes are removed, because only this situation will cause a violation of the nature (Nature 5, and perhaps Nature 4).

As with the insertion node, the red-black tree deletes the node and performs the removal of the binary search tree first.

void Deletefromrbtree (Tree *tree, node *node) {if (node = = tree->nil) Return;int Node_original_color = node->color; Node *changenode = node;if (Node->left = = Tree->nil) {Changenode = Node->right;transplant (tree, node, node-> right);} else if (node->right = = Tree->nil) {Changenode = Node->left;transplant (tree, node, node->left);} Else{tree t;t.root = Node->right;t.nil = tree->nil; Node *min = Rbminimum (&t); Node *end = Min->right;node_original_color = Min->color;changenode = End;min->size = node->size-1;if (node = = tree->root) Tree->root = min;if (node->right! = min) {rbtransplant (tree, Min, min->right); min->right = node->right;node->right->parent = min;} Min->left = node->left;node->left->parent = min; Rbtransplant (Tree, node, min); min->color = Node->color;} Free (node), if (Node_original_color = = BLACK) {rbdeletefixup (tree, Changenode);}}
We focus primarily on the Deletefromrbtree method at the end, and here we make a judgment, when node_original_color = = BLACK, the Rbdeletefixup method is executed on the Changnode node. Node_original_color records the color of the node that was actually deleted. Changenode points to the node being moved. There are 3 scenarios for removing nodes from a binary search tree, which can be concluded as follows:

Situation 1. The left subtree of the deleted node x is empty,Changenode refers to the right child, Node_original_color is the color of x ;

Situation 2. The right subtree of the deleted node x is empty,changenode points to the left child, and thenode_original_color is the color of x ;

Situation 3. The left and right subtree of the deleted node x is not empty, then the actual node being deleted is actually the posterior drive node of x, Changenode points to they child of the rear drive node of x, andnode_original_color is the color of y . Because Y is the actual node that is being deleted, it may cause a change in the black height of the path that is traced from Y up.

In either case, the resulting changenode is balanced, as it arrives at the leaf node path without the node x.

Note that the above 3 situations are likely to make the changenode point to a nil node, at this time I do you need to first the nil node of the parent node pointer to make corresponding changes, corresponding to the above 3 cases, there are the following 2 kinds of modifications:

The parent node pointer of the case 1,2:nil (Changenode) points to the parent node of the deleted node;

The parent node of the case 3:nil (Changenode) points to the parent node of the post-drive node of the deleted node.

In fact, the above modification of the discussion is a bit superfluous, because it actually with the binary search tree delete operation on the pointer to the modification is exactly the same. Here, I just want to emphasize that we should treat nil nodes as a common leaf node, although we just use it to simplify boundary operations. At this point, in insertions and deletions, we have already explained the role of nil nodes in simplifying boundary operations. All in all, because of the nil node, we no longer have to consider the boundary problem where the parent node of the root node is null, or the child of the leaf node is null.

The code for the Rbdeletefixup method is given first and then interpreted for the code.

void Rbdeletefixup (Tree *tree, Node *x) {while (x! = Tree->root && X->color = = BLACK) {if (x = = x->parent-& Gt;left) {Node *w = x->parent->right;if (W->color = = red) {//Case 1w->color = Black;x->parent->color = red; Leftrotate (tree,x->parent); w = x->parent->right;} if (W->left->color = = Black && W->right->color = = Black) {//Case 2w->color = Red;x = x->parent;} Else{if (W->right->color = = BLACK) {//Case 3w->left->color = Black;w->color = Red;rightrotate (tree, w); w = x >parent->right;} Case 4w->color = X->parent->color;x->parent->color = Black;w->right->color = BLACK;leftRotate ( tree, x->parent); x = Tree->root;}} else if (x = = X->parent->right) {//with the above symmetric node *w = x->parent->left;if (W->color = = RED) {w->color = BLACK; X->parent->color = Red;rightrotate (tree, x->parent); w = x->parent->left;} if (W->left->color = = BLACK && W->right->color = = BLACK) {W->color = Red;x = x->parent;} Else{if (W->left->color = = BLACK) {W->right->color = Black;w->color = Red;leftrotate (tree, w); w = x-> Parent->left;} W->color = X->parent->color;x->parent->color = Black;w->left->color = BLACK;rightRotate (tree, X- >parent); x = Tree->root;}}} X->color = BLACK;}
For the deletion of nodes in 3 cases, the adjustment of Changenode has different situation:

(1). deleted node x only one child

At this time x child Changenode will take their children to replace X, if the changenode is black, then the changenode to the upper path of the black height will be deleted because of x 1 less, causing the tree imbalance, The treatment of this situation will be described later, if the changenode is red, we only need to simply modify the Changenode as Black to solve the problem;

(2). Deleted node X has two children

At this point x will be replaced by X's rear drive node y, where y turns into Y's original right child Changenode. Since then, we just need to change the color of Y to black to make Y does not cause the tree imbalance, and then focus on the color of the Changenode , for changenode, you can like the above (1) to deal with.


When Changenode is black, there are 4 cases of changenode processing, the following changenode is called node X, note thatX is always black and balanced :

Situation 1. X's brother node W is red.

After deleting the node, the parent node XP of x is changed by the black height of the path where x reaches the leaf node, and the tree with the root of XP is no longer balanced.

The situation 1,x is balanced, but because the Zuozi of Node B is deleted a black node, resulting in a 1 less black height of the left subtree of Node B, so node B is unbalanced. At this point, ha==hb==hr-1,hr==hd==he==hf. The node B can be left-handed, and then modify the color of Node B and node D to get to the right, converted to conditions 2, 3, 4 for processing.

Situation 2. X's brother node W is black, and the two sub-nodes of W are black.

As in case 1, after the node is deleted, Node B is unbalanced, where ha==hb==hr-1,hr==hd==he==hf. So we can directly modify the node D is black, can make the node B to achieve a balance, but this will make the Node B of the black height of 1 less than the original, will cause node B to the tree imbalance. At this point, if the Node B is red, then the Rbdeletefixup loop will end, then the Node B is modified to black, then the point B of the black to restore the same, do not affect the balance of other trees. If Node B is black, the tree's black height is continuously adjusted upward from that node.

Situation 3. X's brother Knot W is black and W's left child is red, W's right child is black

This is similar to the insertion node scenario 2, which can be rotated to turn it into case 4 for processing.


It is simple to prove that the red-black nature of the junction W is not destroyed when the junction W is right-handed. Before rotation, the junction w is balanced, so hr==hd==he+1==hf+1. After rotation, the junction W points to the end of C, at this point the node W Gow is HR, the right subtree is he+1==hr, so the junction W is still balanced, and then see node d,hd==he+1, so node D is also balanced. To sum up, this rotation does not affect the red and black properties of the right subtree of Node B, merely turning it into 4 for processing.

Situation 4. X's brother Knot W is black, and W's right child is red

To investigate this situation, the first is the same as above, because the deletion of nodes leads to the imbalance of Node B, where hr==hd==he==hf,ha==hb==hr-1. The right image can be obtained by making a left-hand rotation on Node B and modifying the color of nodes B, D, and E. At this point, the node B reaches the balance node D Gow is ha+2, the right subtree black height is he+1==ha+2, so node D is also balanced, the tree from the root of the Hegau before and after the deletion and rotation of the operation is not changed, so will not affect the balance of other trees. That is, after performing the operation of 4, the whole tree should be balanced, unless the rotated node x is the root node, violating the nature of 2. According to the Rbdeletefixup program given above, when x is the root node, it exits the loop and finally the X is dyed black, at which point the whole tree is balanced.


The above 4 cases are for the node X is a left sub-tree, when X is a right subtree, its operation and the above operation is completely symmetrical.

4. Time complexity of insertion and rotation of red and black trees

The red and black tree inserts require O (LG (n)) times, and no more than 2 rotations are made to the adjustment after the insertion node. The rotation of the adjustment after the delete node does not operate 3 times, backtracking up to O (LG (n)) times along the tree. All in all, the time complexity of inserting and deleting red and black trees is O (LG (n)).

c Implementation of the code can refer to my GitHub project, there are some other data structure and algorithm implementation. The project continues to update Oh ~

Data structure and algorithms

Insertion and deletion of red and black trees

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.