Basic Properties of Red-Black Trees

Reproduced in the summary of knowledge of red and black trees.
Original Link: https://blog.csdn.net/xiaofeng10330111/article/details/106080394?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163869533816780357235560%2522%252C%2522scm%2522%253A%252220140713.130102334...%2522%257D&request_id=163869533816780357235560&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2blogtop_positive~default-1-106080394.pc_v2_rank_blog_default&utm_term=%E7%BA%A2%E9%BB%91%E6%A0%91&spm=1018.2226.3001.4450

Catalog

1. Basic Understanding of Red and Black Trees

(1) Understanding the basic definition of red and black trees

(2) Understanding that red-black trees are an approximate balance

1. Remove the red node from the red-black tree and analyze the height of the red-black tree containing the black node

2. Add the red node back and analyze the height change

(3) Comparison of red-black and AVL trees:

2. Analysis of the Basic Ideas of Realizing Red and Black Trees

(1) Understanding the rotate left and right operations

(2) Balance adjustment of insertion operation

Case 1: If the node of interest is a, its uncle node d is red

Situation 2: If the focus node is a, its uncle node d is black, and the focus node a is the right child of its parent node b

Case 3: If the focus node is a, its uncle node d is black, and the focus node a is the left child of its parent node b

The specific code above is as follows:

(3) Balance adjustment of deletion operation

1. Preliminary adjustments for deleting nodes

Scenario 1: If the node to be deleted is a, it has only one child node b

Scenario 2: If node a to be deleted has two non-empty child nodes and its successor node is the right child node c of node a

Scenario 3: If node a is to be deleted, it has two non-empty child nodes, and the successor node of node a is not a right child node

2. Secondary adjustment for nodes of interest

Scenario 1: If node of interest is a, its sibling node c is red

Scenario 2: If node of interest is a, its sibling node c is black, and the left and right child nodes d and e of node c are black

Case 3: If the node of interest is a, its sibling node c is black, its left child d is red, and its right child e is black

Situation 4: If the sibling node c of node a is black and the right child node of c is red

The specific code above is visible:

References and links:

1. Basic Understanding of Red and Black Trees

(1) Understanding the basic definition of red and black trees

Red-Black Tree, or R-B Tree, is an unsecured balanced binary search tree.

Nodes in a red-black tree, one marked black and one marked red. In addition, a red-black tree needs to meet several requirements:

  • The root node is black;
  • Each leaf node is a black, empty node (NIL), which means that the leaf node does not store data (black, empty leaf nodes are omitted from the diagram);
  • No adjacent node can be red at the same time, that is, the red node is separated by the black node;
  • Each node, all paths from that node to its reachable leaf node, contains the same number of black nodes;

(2) Understanding that red-black trees are an approximate balance

The purpose of balancing binary lookup trees is to solve the performance degradation caused by dynamic updates of binary lookup trees. So the term "balance" can be equivalent to not degrading performance. Approximate Balance is equivalent to not degrading performance too severely.

A very balanced binary tree (full or complete) has a height of about log2n, so if you want to prove that the red-black tree is approximately balanced, you only need to analyze whether the height of the red-black tree approaches log2n more steadily.

1. Remove the red node from the red-black tree and analyze the height of the red-black tree containing the black node

When the red node is deleted, some nodes will have no parent, and they will take their grandparent node (the parent node of the parent node) directly as the parent node. So the previous binary tree becomes a quadtree.

When you take some nodes out of the quadtree and place them at the leaf node position, the quadtree becomes a complete binary tree. Therefore, the height of a quadtree containing only black nodes is smaller than that of a complete binary tree containing the same number of nodes.

The height of a complete binary tree is similar to log2n, where the height of a quadruple "black tree" is lower than that of a full binary tree, so the height of a "black tree" without a red node cannot exceed log2n.

2. Add the red node back and analyze the height change

In a red-black tree, a red node cannot be adjacent, that is, a red node must have at least one black node, separating it from other red nodes.

The path with the most black nodes in the red-black tree will not exceed log2n, so when the red node is added, the longest path will not exceed 2log2n, that is, the height of the red-black tree is approximately 2log2n.

Therefore, the height of the red-black tree is only twice as high as the height of the highly balanced AVL tree (log2n), and there is not much decline in performance. The results derived in this way are not accurate enough, in fact, the performance of red and black trees is better.

(3) Comparison of red-black and AVL trees:

  • AVL trees are better than red and black trees in time complexity, but for today's computers, the cpu is too fast to ignore performance differences
  • Insertion and deletion of red and black trees are easier to control than AVL trees
  • The overall performance of red-black trees is slightly better than that of AVL trees (red-black trees rotate less than AVL trees).

2. Analysis of the Basic Ideas of Realizing Red and Black Trees

The balancing process of the red and black trees is very similar to the recovery of the Rubik's Cube. The general process is: what kind of node arrangement do we have to adjust. As long as these fixed adjustment rules are followed, an unbalanced red-black tree can be balanced.

As mentioned above, among the four basic requirements for a qualified red-black tree, the third and fourth requirements may be destroyed in the process of inserting and deleting nodes, while the "balance adjustment" is actually to restore the third and fourth points destroyed. Specific analysis is as follows:

(1) Understanding the rotate left and right operations

Left-handed means left-handed around a node. A, b and r in the graph represent subtrees and can be empty.

Code implementation:

   
  1. /**
  2. * Function description: balance is required on left-to-right side
  3. *
  4. * @author yanfengzhang
  5. * @date 2020-05-27 14:57
  6. */
  7. private void rotateLeft (Entry<K, V> p) {
  8. if (p != null) {
  9. /*Get the right child of the root node */
  10. Entry<K, V> r = p.right;
  11. /*Assign a value to the left node of the right child of the root node*/
  12. p.right = r.left;
  13. if (r.left != null)
  14. /*Assign the value of root node to the currently disconnected following node*/ {
  15. r.left.parent = p;
  16. }
  17. /*r p.parent is the root of the new root node in the future, making it the new root node */
  18. r.parent = p.parent;
  19. if (p.parent == null) {
  20. root = r;
  21. }
  22. /*If p is a left child, let him be a left child as well*/
  23. else if (p.parent.left == p) {
  24. p.parent.left = r;
  25. } else {
  26. p.parent.right = r;
  27. }
  28. /*The last converted value of the current exchange*/
  29. r.left = p;
  30. p.parent = r;
  31. }
  32. }

Right-handed means right-handed around a node. A, b and r in the graph represent subtrees and can be empty.

Code implementation:

   
  1. /**
  2. * Function description: Right hand code
  3. *
  4. * @author yanfengzhang
  5. * @date 2020-05-27 14:58
  6. */
  7. private void rotateRight (Entry<K, V> p) {
  8. if (p != null) {
  9. Entry<K, V> l = p.left;
  10. p.left = l.right;
  11. if (l.right != null) {
  12. l.right.parent = p;
  13. }
  14. l.parent = p.parent;
  15. if (p.parent == null) {
  16. root = l;
  17. } else if (p.parent.right == p) {
  18. p.parent.right = l;
  19. } else {
  20. p.parent.left = l;
  21. }
  22. l.right = p;
  23. p.parent = l;
  24. }
  25. }

(2) Balance adjustment of insertion operation

The red-black tree specifies that the inserted nodes must be red. Moreover, the newly inserted nodes in the binary search tree are placed on the leaf nodes.

There are two special cases of balance adjustment for insertion operations:

  • If the parent node of the inserted node is black, we don't need to do anything, it still satisfies the red-black tree definition.
  • If the inserted node is the root node, we can change its color directly and make it black.

In addition, other situations violate the definition of red and black trees and need to be adjusted, which involves two basic operations: left-right rotation and color change.

The balance adjustment process of red and black trees is an iterative process. Call the node being processed the node of interest. The nodes of interest change as they iterate over and over. The first node of interest is the newly inserted node. After inserting a new node, if the balance of the red and black trees is broken, there are generally three situations:

Note: We just need to keep adjusting according to the characteristics of each situation to keep the red and black trees in line with the definition, that is, to keep the balance. To simplify the description, the sibling node of the parent node is called the uncle node, and the parent node of the parent node is called the grandparent node.

Case 1: If the node of interest is a, its uncle node d is red

This is done by setting the color of the parent node b and uncle node d of node a to black. Set the color of the grandparent node c of node a to red; Focus on node becoming grandparent node c of a; Skip to scenario two or three.

Situation 2: If the focus node is a, its uncle node d is black, and the focus node a is the right child of its parent node b

The specific operations are as follows: the focus node becomes the parent node B of node a; Turn left around the new focus node b; Jump to scenario three.

Case 3: If the focus node is a, its uncle node d is black, and the focus node a is the left child of its parent node b

The specific operations are as follows: right-hand around the grandparent node c of node a; Change the color of parent node b and sibling node c of node a to end the adjustment.

The specific code above is as follows:

   
  1. /**
  2. * Function description: Insert a node
  3. *
  4. * @author yanfengzhang
  5. * @date 2020-05-27 15:07
  6. */
  7. private void insert (RBTreeNode<T> node) {
  8. int cmp;
  9. RBTreeNode<T> root = this.rootNode;
  10. RBTreeNode<T> parent = null;
  11. /*Under which parent node the anchor node is added*/
  12. while ( null != root) {
  13. parent = root;
  14. cmp = node.key.compareTo(root.key);
  15. if (cmp < 0) {
  16. root = root.left;
  17. } else {
  18. root = root.right;
  19. }
  20. }
  21. node.parent = parent;
  22. /*Indicates that there is currently no node, then the new node is the root node*/
  23. if ( null == parent) {
  24. this.rootNode = node;
  25. } else {
  26. //Find the location of the new node under the current parent node
  27. cmp = node.key.compareTo(parent.key);
  28. if (cmp < 0) {
  29. parent.left = node;
  30. } else {
  31. parent.right = node;
  32. }
  33. }
  34. /*Set the color of the inserted node to red*/
  35. node.color = COLOR_RED;
  36. /*Fix to Black and Red Tree*/
  37. insertFixUp(node);
  38. }
  39. /**
  40. * Function Description: Red and Black Tree Insert Fix
  41. *
  42. * @author yanfengzhang
  43. * @date 2020-05-27 15:07
  44. */
  45. private void insertFixUp (RBTreeNode<T> node) {
  46. RBTreeNode<T> parent, gparent;
  47. /*The parent node of the node exists and is red*/
  48. while (((parent = getParent(node)) != null) && isRed(parent)) {
  49. gparent = getParent(parent);
  50. /*What if its grandparent node is empty, if it is the left child of the grandparent node*/
  51. if (parent == gparent.left) {
  52. RBTreeNode<T> uncle = gparent.right;
  53. if (( null != uncle) && isRed(uncle)) {
  54. setColorBlack(uncle);
  55. setColorBlack(parent);
  56. setColorRed(gparent);
  57. node = gparent;
  58. continue;
  59. }
  60. if (parent.right == node) {
  61. RBTreeNode<T> tmp;
  62. leftRotate(parent);
  63. tmp = parent;
  64. parent = node;
  65. node = tmp;
  66. }
  67. setColorBlack(parent);
  68. setColorRed(gparent);
  69. rightRotate(gparent);
  70. } else {
  71. RBTreeNode<T> uncle = gparent.left;
  72. if (( null != uncle) && isRed(uncle)) {
  73. setColorBlack(uncle);
  74. setColorBlack(parent);
  75. setColorRed(gparent);
  76. node = gparent;
  77. continue;
  78. }
  79. if (parent.left == node) {
  80. RBTreeNode<T> tmp;
  81. rightRotate(parent);
  82. tmp = parent;
  83. parent = node;
  84. node = tmp;
  85. }
  86. setColorBlack(parent);
  87. setColorRed(gparent);
  88. leftRotate(gparent);
  89. }
  90. }
  91. setColorBlack( this.rootNode);
  92. }

(3) Balance adjustment of deletion operation

The balancing adjustment of the delete operation is divided into two steps:

The first step is to make initial adjustments to delete nodes. The preliminary adjustment only guarantees that the whole red-black tree will meet the last defined requirement after one node is deleted, that is, every node, all paths from that node to its reachable leaf nodes, contains the same number of black nodes;

The second step is to make a secondary adjustment to the node of interest so that it satisfies the third definition of the red-black tree, that is, there are no two adjacent red nodes.

1. Preliminary adjustments for deleting nodes

The definition of red-black tree contains only red and black nodes. After preliminary adjustment, some nodes will be marked in two colors, red-black or black-black, in order to meet the last requirements of the definition of red-black tree. If a node is marked as black-black, it is counted as two black nodes when counting the number of black nodes.

Note: If a node can be either red or black, the figure is represented by half red and half black. If a node is red-black or black-black, the extra black is represented by a small black dot in the upper left corner.

Scenario 1: If the node to be deleted is a, it has only one child node b

The specific operations are as follows: delete node A and replace node b with the position of node a, which is the same as the normal deletion of a binary search tree; Node a can only be black, node b can only be red, otherwise it does not fit the definition of red-black tree. In this case, we change node b to black; Adjustment is complete, no secondary adjustment is required.

Scenario 2: If node a to be deleted has two non-empty child nodes and its successor node is the right child node c of node a

This is done as follows: if the successor node of node a is the right child node c, then the right child node C must not have a left subtree. We delete node A and replace node C with the location of node a. This part of the operation is the same as deleting a binary search tree. Then set the color of node C to be the same as that of node a. If node C is black, in order not to violate the last definition of the red-black tree, we add an extra black to the right child node D of node c, at which time node D becomes either "red-black" or "black-black"; At this point, the focus node becomes node d, and the second step of adjustment will be for the focus node.

Scenario 3: If node a is to be deleted, it has two non-empty child nodes, and the successor node of node a is not a right child node

The specific operations are as follows: find the succeeding node d, delete it, delete the succeeding node D process refers to CASE 1; Replace node a with successor node d; Set the color of node d to be the same as that of node a; If node D is black, in order not to violate the last definition of the red-black tree, we add a black to the right child node C of node d, at which time node C becomes either "red-black" or "black-black"; At this point, the focus node becomes node c, and the second step of adjustment will be for the focus node.

2. Secondary adjustment for nodes of interest

After the initial adjustment, the focus node becomes a red-black or BLACK-BLACK node. For this node of interest, there are four cases to make secondary adjustments.

Note: The secondary adjustment is to make no adjacent red nodes in the red-black tree.

Scenario 1: If node of interest is a, its sibling node c is red

Actions: Rotate left around the parent node b of node a; Note that node a's parent node b and grandparent node c exchange colors; The focus node is unchanged; Continue to select the appropriate rule from the four cases to adjust.

Scenario 2: If node of interest is a, its sibling node c is black, and the left and right child nodes d and e of node c are black

Specific operations: turn the color of the sibling node c concerned with node a to red; Remove a black from node a of interest, where node a is pure red or black; Add a black to the parent node B of node a, at which point node B becomes either "red-black" or "black-black"; Focus on the node changing from a to its parent b; Continue to adjust by choosing the rule that meets from four scenarios.

Case 3: If the node of interest is a, its sibling node c is black, its left child d is red, and its right child e is black

Specific operations: turn right around the sibling node c of node a; Node c and node d exchange colors; The focus node is unchanged; Jump to CASE 4 and continue adjusting.

Situation 4: If the sibling node c of node a is black and the right child node of c is red

Actions: Rotate left around the parent node b of node a; Set the color of the sibling node c of node a to be the same as that of the parent node b of node a. Set the color of the parent node b of node a to black; By removing a black from node a of interest, node a becomes pure red or black; Set uncle node e of node a to black; End of adjustment.

The specific code above is visible:

   
  1. /**
  2. * Function description: Delete node
  3. *
  4. * @author yanfengzhang
  5. * @date 2020-05-27 15:11
  6. */
  7. private void remove (RBTreeNode<T> node) {
  8. RBTreeNode<T> child, parent;
  9. boolean color;
  10. /*Removed node left and right children are not empty*/
  11. if (( null != node.left) && ( null != node.right)) {
  12. /*Get the succeeding node of the deleted node*/
  13. RBTreeNode<T> replace = node;
  14. replace = replace.right;
  15. while ( null != replace.left) {
  16. replace = replace.left;
  17. }
  18. /*node Node is not root*/
  19. if ( null != getParent(node)) {
  20. /*node Is left node*/
  21. if (getParent(node).left == node) {
  22. getParent(node).left = replace;
  23. } else {
  24. getParent(node).right = replace;
  25. }
  26. } else {
  27. this.rootNode = replace;
  28. }
  29. child = replace.right;
  30. parent = getParent(replace);
  31. color = getColor(replace);
  32. if (parent == node) {
  33. parent = replace;
  34. } else {
  35. if ( null != child) {
  36. setParent(child, parent);
  37. }
  38. parent.left = child;
  39. replace.right = node.right;
  40. setParent(node.right, replace);
  41. }
  42. replace.parent = node.parent;
  43. replace.color = node.color;
  44. replace.left = node.left;
  45. node.left.parent = replace;
  46. if (color == COLOR_BLACK) {
  47. removeFixUp(child, parent);
  48. }
  49. node = null;
  50. return;
  51. }
  52. if ( null != node.left) {
  53. child = node.left;
  54. } else {
  55. child = node.right;
  56. }
  57. parent = node.parent;
  58. color = node.color;
  59. if ( null != child) {
  60. child.parent = parent;
  61. }
  62. if ( null != parent) {
  63. if (parent.left == node) {
  64. parent.left = child;
  65. } else {
  66. parent.right = child;
  67. }
  68. } else {
  69. this.rootNode = child;
  70. }
  71. if (color == COLOR_BLACK) {
  72. removeFixUp(child, parent);
  73. }
  74. node = null;
  75. }
  76. /**
  77. * Function Description: Delete Repair
  78. *
  79. * @author yanfengzhang
  80. * @date 2020-05-27 15:11
  81. */
  82. private void removeFixUp (RBTreeNode<T> node, RBTreeNode<T> parent) {
  83. RBTreeNode<T> other;
  84. /*node Not empty and black, and not root node*/
  85. while (( null == node || isBlack(node)) && (node != this.rootNode)) {
  86. /*node Is the left child of the parent node*/
  87. if (node == parent.left) {
  88. /*Get their right child*/
  89. other = parent.right;
  90. /*node The sibling node of the node is red*/
  91. if (isRed(other)) {
  92. setColorBlack(other);
  93. setColorRed(parent);
  94. leftRotate(parent);
  95. other = parent.right;
  96. }
  97. /*node The sibling node of the node is black, and the two child nodes of the sibling node are also black*/
  98. if ((other.left == null || isBlack(other.left)) &&
  99. (other.right == null || isBlack(other.right))) {
  100. setColorRed(other);
  101. node = parent;
  102. parent = getParent(node);
  103. } else {
  104. /*node The sibling node of the node is black, and the right child of the sibling node is red*/
  105. if ( null == other.right || isBlack(other.right)) {
  106. setColorBlack(other.left);
  107. setColorRed(other);
  108. rightRotate(other);
  109. other = parent.right;
  110. }
  111. /*node The sibling node of the node is black, and the right child of the sibling node is red, and the left child is any color*/
  112. setColor(other, getColor(parent));
  113. setColorBlack(parent);
  114. setColorBlack(other.right);
  115. leftRotate(parent);
  116. node = this.rootNode;
  117. break;
  118. }
  119. } else {
  120. other = parent.left;
  121. if (isRed(other)) {
  122. setColorBlack(other);
  123. setColorRed(parent);
  124. rightRotate(parent);
  125. other = parent.left;
  126. }
  127. if (( null == other.left || isBlack(other.left)) &&
  128. ( null == other.right || isBlack(other.right))) {
  129. setColorRed(other);
  130. node = parent;
  131. parent = getParent(node);
  132. } else {
  133. if ( null == other.left || isBlack(other.left)) {
  134. setColorBlack(other.right);
  135. setColorRed(other);
  136. leftRotate(other);
  137. other = parent.left;
  138. }
  139. setColor(other, getColor(parent));
  140. setColorBlack(parent);
  141. setColorBlack(other.left);
  142. rightRotate(parent);
  143. node = this.rootNode;
  144. break;
  145. }
  146. }
  147. }
  148. if (node != null) {
  149. setColorBlack(node);
  150. }
  151. }

References and links:

1.https://tech.meituan.com/2016/12/02/redblack-tree.html

2. The Beauty of Data Structure and Algorithms, Wang Zheng (Former Google Engineer), Geek Time, 2019

3.https://blog.csdn.net/tanrui519521/article/details/80980135

4.https://blog.csdn.net/jjc120074203/article/details/78780221

5.https://blog.csdn.net/aa1215018028/article/details/92660140

Tags: data structure

Posted on Sun, 05 Dec 2021 16:19:23 -0500 by larissahn