首先,在阅读文章之前,我希望读者对二叉树有一定的了解,因为红黑树的本质就是一颗二叉树。所以本篇博客中不在将二叉树的增删查的基本操作了,需要了解的同学可以到我之前写的一篇关于二叉树基本操作的博客:https://www.cnblogs.com/rainple/p/9970760.html

  有随机数节点组成的二叉树的平均高度为logn,所以正常情况下二叉树查找的时间复杂度为O(logn)。但是,根据二叉树的特性,在最坏的情况下,比如存储的是一个有序的数据的话,那么所以的数据都会形成一条链,此时二叉树的深度为n,时间复杂度为O(n)。红黑树就是为了解决这个问题的,它能够保证在任何情况下树的深度都保持在logn左右,红黑树通过一下约束来完成这个特性:

  1、每个节点不是红色就是黑色。

  2、根节点为黑色。

  3、每个叶子节点都是黑色的。

  4、每个红色节点的子节点都是黑色。

  5、任意节点,到其任意叶节点的所有路径都包含相同的黑色节点。

  结构如下图:

  红黑树的基本操作包括删除和添加。在删除或者添加一个节点的时候就有可能打破原有的红黑树维持的平衡,那么就需要通过着色和旋转的方式来使红黑树重新达到平衡。着色是非常简单的,直接将节点的颜色改变就可以了,多以要理解红黑树,就必须需要懂得如何进行旋转,旋转又分为左旋和右转,两个操作相反的,所以理解了一个旋转的操作就很容易理解另一个旋转了。

  左旋:

  

  如图所示,红色节点为旋转支点,支点往左子树移动即为左旋。左旋之后我们可以看到原支点的位置被原支点的右子节点代替,新支点的左子节点变为了原来为父节点的原支点,新支点的左子节点变为原支点的右子节点,因此左旋操作总共右3个节点,以为旋转前的结构举例,分别为红色节点(原支点),黄色节点(新支点)和L节点。Java代码实现如下:

  1.   /**
  2. * 左旋
  3. * @param e 支点
  4. */
  5. private void leftRotate(Entry<K,V> e){
  6. //支点的右子节点
  7. Entry<K,V> right = e.right;
  8. //支点右子节点的左子节点
  9. Entry<K,V> rightOfLeft = right.left;
  10. //新旧支点的替换
  11. right.parent = e.parent;
  12. if (e.parent == null){
  13. root = right;
  14. }else {
  15. if (e == e.parent.left)
  16. e.parent.left = right;
  17. else
  18. e.parent.right = right;
  19. }
  20. //将原支点变为新支点的左节点
  21. right.left = e;
  22. e.parent = right;
  23. //将新支点的左节点变为就支点的右节点
  24. e.right = rightOfLeft;
  25. if (rightOfLeft != null)
  26. rightOfLeft.parent = e;
  27. }

  因为在红黑树中每个节点都有一个指针指向自己的父节点,父节点也有指针指向子节点,因为在改动一个节点的时候都需要分别改动当前节点和父节点的指向,结合左旋的示意图,用Java代码实现起来就不会很困难了。

  右旋

  

    右旋操作和左旋相反的,两者互反。依然是红色作为旋转支点,右旋后黄色节点代替了红色节点原来的位置,黄色节点的右节点旋转后变为红色节点的左节点。Java 代码实现如下:

  1. /**
  2. * 右旋
  3. * @param e 旋转支点
  4. */
  5. private void rightRotate(Entry<K,V> e){
  6. //原支点的左节点
  7. Entry<K,V> left = e.left;
  8. //原支点的左节点的右节点
  9. Entry<K,V> leftOfRight = left.right;
  10. //新旧支点的替换
  11. left.parent = e.parent;
  12. if (e.parent == null){//支点的父节点为根节点的情况
  13. root = left;
  14. }else {//非跟节点
  15. if (e == e.parent.left)
  16. e.parent.left = left;
  17. else
  18. e.parent.right = left;
  19. }
  20. //将原支点变为新支点的右节点
  21. left.right = e;
  22. e.parent = left;
  23. //将新支点未旋转前的右节点变为转换后的原支点的左节点
  24. e.left = leftOfRight;
  25. if (leftOfRight != null)
  26. leftOfRight.parent = e;
  27. }

  添加节点

  首先,在进入主题之前我们再来回顾一下红黑树的5个特点:

  1、每个节点不是红色就是黑色。

  2、根节点为黑色。

  3、每个叶子节点都是黑色的。

  4、每个红色节点的子节点都是黑色。

  5、任意节点,到其任意叶节点的所有路径都包含相同的黑色节点。

  红黑树插入节点与二叉树是一致的,所以每次添加节点肯定是添加到叶子节点上,具体步骤如下:

  第一步:将新节点插入到红黑树中。

  第二步:将新节点设置为红色。这里为什么需要设置成红色呢?主要是为了满足特性5,这样在插入节点后就少解决了一个冲突,也就少一点麻烦。插入完成后,我们来看一下还有那些特性是有可能发生冲突的,特性1每个节点不是红色就是黑色的,这明显没有冲突,特性2根节点为黑色,当插入节点为根节点的时候就会有冲突了,这种就很简单了,直接将根节点着色为黑色即可。特性3每个叶子节点都是黑色,这个明显没有冲突。特性4每个红色节点的子节点都是黑色的,这个特性就有可能会冲突,因为在插入新节点的时候我们无法确定新节点的父节点的颜色是黑色的还是红色,如果新节点的父节为黑色,那么就不会有冲突,否则就会违背了特性4。特性5任意节点,到其任意子节点的所有路径都包含相同的黑色节点,因为我们插入的新节点被着色为红色,所以并不会影响到每个路径的黑色节点的数量,因此也不会有冲突。综上所诉,那么在插入新节点的时候,只有特性4有可能发生冲突。

  第三步:平衡红黑树,使之成为新的红黑树。

  根据第二部得到的结论,我们可以知道只有情况是需要解决冲突的,那就是新节点的父节点为红色的时候违背了特性4。接下来我们将要讨论这个问题,因为在新插入一个节点之前是一颗已经平衡了的红黑树,因此根据特新4,新节点的祖父节点必定为黑色。根据这种情况,我们又可以分为以下四种情况:

  情况1:新节点为左节点,叔叔节点为红色;

  情况2:新节点为左节点,叔叔节点为黑色;

  情况3:新节点为右节点,叔叔节点为红色;

  情况4:新节点为右节点,叔叔节点为黑色;

  情况1和情况3的情况是一样的,所以我们可以将这两种情况看作是一种情况,这个情况我们稍后再讨论,然后看一下情况2和情况4,通过左旋就可以转换成情况2。

  综上所述,我们可以归结为3中情况:

  情况1:叔叔节点是红色节点;

  情况2:叔叔节点是黑色节点,新节点为右节点;

  情况3:叔叔节点是黑色节点,新节点为左节点;

  上面我也有提到,当插入新节点时肯定是属于第一种情况的,然后2、3由1转换而来,在此之前我希望你之前已经了解过递归的原理和思想,把局部看作整体的思想,因为这将有助于下面讨论的理解。下面我们将要继续分析这三种情况,情况1这种情况处理起来比比较简单,只需要将祖父节点变为红色节点,父节点和叔叔节点变为黑色即可,这仅仅只是当整个红黑树只有这几个节点的时候是可以了,但事实并非如此,这仅仅只是达到了局部平衡。

  上图,我们看到已经达到了局部的平衡,但是,我们还会有其他的情况,那就是祖父节点有可能也会有父节点。那么又会有两种情况,1是祖父节点的父节点可能是黑色的,2是可能是红色的,如果黑色那么整个红黑树就达到平衡了。不知道大家根觉到了没有,这两种情况是不是跟新插入一个节点的情况是一致的,是不是又回到了插入新节点的问题了?于是我将局部收到影响的部分画出来,如图:

  图a就是将情况1从新着色后的部分受影响的节点,当然只是其中的一种情况,此时我们将已经平衡的部分去掉就变成的图b的情况,这种情况是不是很熟悉呢?我们的祖父节点当成新节点,是不是相当于上面讨论的情况1呢?不过与上面讨论的情况不同的是,这里3中可能情况都可能出现,因为叔叔节点有可能为红色或黑色。所以这时候才有可能出现真正的三种情况:

  情况1:叔叔节点是红色节点;

  情况2:叔叔节点是黑色节点,新节点为右节点;

  情况3:叔叔节点是黑色节点,新节点为左节点;

  如果为情况1的话,我们一层一层的往上平衡就可以了,当祖父节点为根节点的时候,我们直接将根节点着色为黑色即可,因为祖父节点的两个子节点都是黑色的,所以变为黑色后仍然是平衡的。接下来我们来讨论下情况2和3。

  很明显的,这两种情况的右节点多出了一个黑色节点,这种情况是在情况1向上着色的时候造成的,即祖父节点由黑色节点变为了红色节点。情况2以父节点为支点左旋,然后将父节点和新节点互换可以得到情况3:

  情况3进行的操作是,首先将父节点着色为黑色,祖父节点着色为红色,然后以祖父为支点进行右旋

  情况3旋转结束后整棵红黑也已经重新恢复平衡了。单从部分其实并看不出已经平衡了,我们可以将三个情况连起来就可以看到了,如下图:

  上图中都是以n节点为参考点的,其余无关的节点就不标出来了。n节点即为插入节点,但是除了第一次操作n节点为真正的新节点,此后的操作所指的n节点只是有助于我们的理解把他当成新节点。当然,这只是其中的一种情况,其他其他的情况可以通过不断向上旋转或着色,最终也会达到这种情况或者顶部是p节点为根节点的时候,第二种情况直接将根节点着色为黑色即可。

  总结:

  回顾一下红黑树的5个特性:

  1、节点不是红色就是黑色。

  2、根节点为黑色。

  3、叶子节点为黑色。

  4、每个红色节点其子节点必须是黑色节点。

  5、任意节点到到其任意的子节点的所有路径的黑色节点的数量相等。

  在插入新节点的时候很显然,不会违背1和3,如果插入的是根节点直接将根节点着色为黑色即可,这种情况可以忽略不计,所以插入节点时可能会违背了4和5,又因为插入的是红色节点因此5也不会违背,最后在插入新节点的时候我们只需要关注特性4就可以了。当父节点为红色的时候跟4有冲突,所以我们接下来讨论的就是这种情况。我们知道,在插入新节点之前整颗红黑树是平衡的,因此可以得出一个结论就是祖父节点肯定肯定是黑色的。我们现在只关注相关的节点即可,目前,我们知道了祖父的节点为黑色,父节点为红色,但是叔叔节点的颜色不知道,新节点的位置也不能确定,所以有2x2中情况,当叔叔节点为红色的时候,两种情况的处理方式是一致的,所以最后我们可以总结为3中情况:

  1、叔叔节点为红色

  2、新节点为右节点,叔叔节点为黑色

  3、新节点为左节点,叔叔节点为黑色

类型 描述 步骤 示意图
情况1 叔叔节点为红色

1、父节点设为黑色

2、叔叔节点设为黑色

3、祖父节点设为红色

4、把祖父节点设置为新节点(当前节点)

情况2 新节点为右节点,叔叔节点为黑色

1、以父节点为支点左旋

2、父节点和新节点互换位置

3、把父节点设为当前节点

 

情况3 新节点为左节点,叔叔节点为黑色

1、父节点设为黑色

2、祖父节点设为红色

3、以祖父节点为支点右旋

 

整合

  树a就是表中的情况1,通过着色后直接转换成了情况3,情况3进行着色旋转后达到了平衡,当树b中的叔叔节点为红色的时候与树a一致,循环调用树a的处理方式,直至达到树b的情况或者树a中的祖父节点到达了根节点,这时候将祖父节点设为黑色即可。

  这种情况就是由情况1转情况2再转情况3,由情况3重新着色旋转后达到平衡。

  需要注意的是:不是每次插入节点都会出现3中情况,有可能只出现了2和3,或者只出现了3一种情况。

  上面是讨论左子树的问题,因为红黑色具有堆成性,因此在处理右子树的时候与处理左子树相反即可。Java代码示例如下:

  1. /**
  2. * 插入新节点后平衡红黑树
  3. * @param e 新节点
  4. */
  5. private void fixAfterInsertion(Entry<K, V> e) {
  6. //将新插入节点设置为红色
  7. setRed(e);
  8. Entry<K,V> p,g,u;//父节点和祖父节点和叔叔节点
  9. Entry<K,V> current = e;//新节点
  10. /**
  11. * 这里通过循环不断向上平衡
  12. */
  13. while ((p = parentOf(current)) != null && isRed(p)){
  14. g = parentOf(p);//祖父节点
  15. if (p == g.left){
  16. u = g.right;
  17. //情况1:叔叔节点为红色
  18. if (u != null && isRed(u)){
  19. setBlack(p);//父节点设为黑色
  20. setBlack(u);//叔叔节点设为黑色
  21. setRed(g);//祖父节点设为红色
  22. current = g;//把祖父节点设为当前节点
  23. //继续向上平衡
  24. continue;
  25. }
  26. //情况2:当前节点为右节点,叔叔节点为黑色
  27. if (current == p.right){
  28. leftRotate(p);//父节点为支点左旋
  29. Entry<K,V> tmp = p;
  30. p = current;//父节点和当前节点互换
  31. current = tmp;//父节点设为当前节点
  32. }
  33. //情况3:当前节点为左节点,叔叔节点为黑色
  34. setBlack(p);//父节点设为黑色
  35. setRed(g);//祖父节点设为红色
  36. rightRotate(g);//祖父节点为支点右旋
  37. }else {//相反的操作
  38. u = g.left;
  39. if (u != null && isRed(u)){
  40. setBlack(p);
  41. setBlack(u);
  42. setRed(g);
  43. current = g;
  44. continue;
  45. }
  46. if (current == p.left){
  47. rightRotate(p);
  48. Entry<K,V> tmp = p;
  49. p = current;
  50. current = tmp;
  51. }
  52. setBlack(p);
  53. setRed(g);
  54. leftRotate(g);
  55. }
  56. }
  57. //最后将根节点设置为红色
  58. setBlack(root);
  59. }

  删除节点

  在二叉树分析一文中已经说过,删除一个节点的时候有3中情况:

  1、删除节点没有子节点

  2、删除节点只有一个子节点

  3、删除节点有两个子节点

  首先,我们逐个来分析每种情况删除节点后对整颗红黑树的平衡性的影响。在删除节点时候红黑树的特性1,2,3肯定不会违背,所以只需要考虑特性4,5即可。

  对于情况1,肯定不会违背特性4,如果删除节点为红色,那么对整颗红黑树的平衡性都不会影响,如果是黑色则违背了特性5,我们先将这种情况记录下来,稍后再进一步讨论。

  对于情况2,有可能删除的是左子树或右子树,暂且不讨论。如果删除的节点为红色,不影响平衡性,如果删除的是黑色,那么肯定会和特性5有冲突,当删除节点的父节点为红色,子节点为红色是也和特性4有冲突。

  对于情况3,其实最后删除的是它的替代节点,根据替代节点的特点,最终其实是回到了1这种情况或者情况2。

  总结上面的3种情况可得到一个结论,只有删除节点为黑色时才会破坏红黑树原来的平衡,因在删除节点之前红黑树是出于平衡状态的,删除之后很明显的其兄弟节点分支必然比删除节点的分支多了一个黑色的节点,因此我们只需要改变兄弟节点的颜色即可,我们只讨论左节点,右节点对称。

  一、删除节点的兄弟节点是红色

  将兄弟节点设为黑色,父节点设为红色,以父节点为支点左旋转,然后将父节点的右节点放到兄弟节点上:

  

  二、兄弟节点是黑色的,兄弟的两个子节点也都是黑色的

  兄弟节点设为红色,把父节点设置为新的删除节点:

  

  三、兄弟节点是黑色的,且兄弟节点的左子节点是红色,右子节点是黑色

  将兄弟节点的左子节点设为黑色,兄弟节点设为红色,以兄弟节点为支点右旋,把父节点的右节点设置为兄弟节点

  

  四、兄弟节点是黑色的,且兄弟节点的右子节点是红色,左子节点任意颜色

  把兄弟节点的设为父节点的颜色,父节点设为黑色,父节点的右节点设为黑色,父节点为支点左旋

  删除的Java代码示例:

  1. public V remove(Object key){
  2. if (key == null) return null;
  3. Entry<K,V> delEntry;
  4. delEntry = getEntry(key);
  5. if (delEntry == null) return null;
  6. size--;
  7. Entry<K,V> p = delEntry.parent;
  8. if (delEntry.right == null && delEntry.left == null){
  9. if (p == null){
  10. root = null;
  11. }else {
  12. if (p.left == delEntry){
  13. p.left = null;
  14. }else {
  15. p.right = null;
  16. }
  17. }
  18. }else if (delEntry.right == null){//只有左节点
  19. Entry<K,V> lc = delEntry.left;
  20. if (p == null) {
  21. lc.parent = null;
  22. root = lc;
  23. } else {
  24. if (delEntry == p.left){
  25. p.left = lc;
  26. }else {
  27. p.right = lc;
  28. }
  29. lc.parent = p;
  30. }
  31. }else if (delEntry.left == null){//只有右节点
  32. Entry<K,V> rc = delEntry.right;
  33. if (p == null) {
  34. rc.parent = null;
  35. root = rc;
  36. }else {
  37. if (delEntry == p.left)
  38. p.left = rc;
  39. else
  40. p.right = rc;
  41. rc.parent = p;
  42. }
  43. }else {//有两个节点,找到后继节点,将值赋给删除节点,然后将后继节点删除掉即可
  44. Entry<K,V> successor = successor(delEntry);//获取到后继节点
  45. boolean color = successor.color;
  46. V old = delEntry.value;
  47. delEntry.value = successor.value;
  48. delEntry.key = successor.key;
  49. if (delEntry.right == successor){//后继节点为右子节点,
  50. if (successor.right != null) {//右子节点有右子节点
  51. delEntry.right = successor.right;
  52. successor.right.parent = delEntry;
  53. }else {//右子节点没有子节点
  54. delEntry.right = null;
  55. }
  56. }else {
  57. successor.parent.left = null;
  58. }
  59. if (color == BLACK)
  60. //fixUpAfterRemove(child,parent);
  61. return old;
  62. }
  63. V old = delEntry.value;
  64. if (delEntry.color == BLACK)//删除为黑色时,需要重新平衡树
  65. if (delEntry.right != null)//删除节点的子节点只有右节点
  66. fixUpAfterRemove(delEntry.right,delEntry.parent);
  67. else if (delEntry.left != null)//删除节点只有左节点
  68. fixUpAfterRemove(delEntry.left,delEntry.parent);
  69. else
  70. fixUpAfterRemove(null,delEntry.parent);
  71. delEntry.parent = null;
  72. delEntry.left = null;
  73. delEntry.right = null;
  74. return old;
  75. }
  76.  
  77. private Entry<K, V> getEntry(Object key) {
  78. if (key == null) return null;
  79. Entry<K, V> delEntry = null;
  80. Entry<K, V> current = root;
  81. int ret;
  82. if (comparator == null){
  83. Comparable<K> k = (Comparable<K>) key;
  84. while (current != null){
  85. ret = k.compareTo(current.key);
  86. if (ret < )
  87. current = current.left;
  88. else if (ret > )
  89. current = current.right;
  90. else{
  91. delEntry = current;
  92. break;
  93. }
  94. }
  95. }else {
  96. for (;current != null;){
  97. ret = comparator.compare(current.key, (K) key);
  98. if (ret < )
  99. current = current.left;
  100. else if (ret > )
  101. current = current.right;
  102. else{
  103. delEntry = current;
  104. break;
  105. }
  106. }
  107. }
  108. return delEntry;
  109. }
  110.  
  111. //node表示待修正的节点,即后继节点的子节点(因为后继节点被挪到删除节点的位置去了)
  112. private void fixUpAfterRemove(Entry<K, V> node,Entry<K,V> parent) {
  113. Entry<K,V> other;
  114. while((node == null || isBlack(node)) && (node != root)) {
  115. if(parent.left == node) { //node是左子节点,下面else与这里的刚好相反
  116. other = parent.right; //node的兄弟节点
  117. if(isRed(other)) { //case1: node的兄弟节点other是红色的
  118. setBlack(other);
  119. setRed(parent);
  120. leftRotate(parent);
  121. other = parent.right;
  122. }
  123.  
  124. //case2: node的兄弟节点other是黑色的,且other的两个子节点也都是黑色的
  125. if((other.left == null || isBlack(other.left)) &&
  126. (other.right == null || isBlack(other.right))) {
  127. setRed(other);
  128. node = parent;
  129. parent = parentOf(node);
  130. } else {
  131. //case3: node的兄弟节点other是黑色的,且other的左子节点是红色,右子节点是黑色
  132. if(other.right == null || isBlack(other.right)) {
  133. setBlack(other.left);
  134. setRed(other);
  135. rightRotate(other);
  136. other = parent.right;
  137. }
  138.  
  139. //case4: node的兄弟节点other是黑色的,且other的右子节点是红色,左子节点任意颜色
  140. setColor(other, colorOf(parent));
  141. setBlack(parent);
  142. setBlack(other.right);
  143. leftRotate(parent);
  144. node = this.root;
  145. break;
  146. }
  147. } else { //与上面的对称
  148. other = parent.left;
  149.  
  150. if (isRed(other)) {
  151. // Case 1: node的兄弟other是红色的
  152. setBlack(other);
  153. setRed(parent);
  154. rightRotate(parent);
  155. other = parent.left;
  156. }
  157.  
  158. if ((other.left==null || isBlack(other.left)) &&
  159. (other.right==null || isBlack(other.right))) {
  160. // Case 2: node的兄弟other是黑色,且other的俩个子节点都是黑色的
  161. setRed(other);
  162. node = parent;
  163. parent = parentOf(node);
  164. } else {
  165.  
  166. if (other.left==null || isBlack(other.left)) {
  167. // Case 3: node的兄弟other是黑色的,并且other的左子节点是红色,右子节点为黑色。
  168. setBlack(other.right);
  169. setRed(other);
  170. leftRotate(other);
  171. other = parent.left;
  172. }
  173.  
  174. // Case 4: node的兄弟other是黑色的;并且other的左子节点是红色的,右子节点任意颜色
  175. setColor(other, colorOf(parent));
  176. setBlack(parent);
  177. setBlack(other.left);
  178. rightRotate(parent);
  179. node = this.root;
  180. break;
  181. }
  182. }
  183. }
  184. if (node!=null)
  185. setBlack(node);
  186. }
  187.  
  188. private Entry<K, V> successor(Entry<K, V> delEntry) {
  189. Entry<K,V> r = delEntry.right;//assert r != null;
  190. while (r.left != null){
  191. r = r.left;
  192. }
  193. return r;
  194. }

  完整的代码示例:

  1. public class MyTreeMap<K,V> {
  2.  
  3. private static final boolean BLACK = true;
  4. private static final boolean RED = false;
  5.  
  6. private Entry<K,V> root;
  7. private int size = ;
  8. private final Comparator<K> comparator;
  9. MyTreeMap(){
  10. comparator =null;
  11. }
  12.  
  13. public MyTreeMap(Comparator comparator){
  14. this.comparator = comparator;
  15. }
  16.  
  17. public V put(K key,V value){
  18. if (root == null){
  19. root = new Entry<>(key,value,null);
  20. size++;
  21. return null;
  22. }else {
  23. int ret = ;
  24. Entry<K,V> p = null;
  25. Entry<K,V> current = root;
  26. if (comparator == null){
  27. if (key == null) throw new NullPointerException("key = null");
  28. Comparable<K> k = (Comparable<K>) key;
  29. while (current != null){
  30. p =current;
  31. ret = k.compareTo(current.key);
  32. if (ret < )
  33. current = current.left;
  34. else if(ret > )
  35. current = current.right;
  36. else {
  37. current.value = value;
  38. return current.value;
  39. }
  40. }
  41. }else {
  42. do {
  43. p = current;
  44. ret = comparator.compare(key,current.key);
  45. if (ret < )
  46. current = current.left;
  47. else if (ret > )
  48. current = current.right;
  49. else {
  50. current.value = value;
  51. return value;
  52. }
  53. }while (current != null);
  54. }
  55. Entry<K,V> e = new Entry<>(key,value,p);
  56. if (ret < )
  57. p.left = e;
  58. else
  59. p.right = e;
  60. size++;
  61. fixAfterInsertion(e);
  62. return e.value;
  63. }
  64. }
  65.  
  66. /**
  67. * 插入新节点后平衡红黑树
  68. * @param e 新节点
  69. */
  70. private void fixAfterInsertion(Entry<K, V> e) {
  71. //将新插入节点设置为红色
  72. setRed(e);
  73. Entry<K,V> p,g,u;//父节点和祖父节点和叔叔节点
  74. Entry<K,V> current = e;//新节点
  75. /**
  76. * 这里通过循环不断向上平衡
  77. */
  78. while ((p = parentOf(current)) != null && isRed(p)){
  79. g = parentOf(p);//祖父节点
  80. if (p == g.left){
  81. u = g.right;
  82. //情况1:叔叔节点为红色
  83. if (u != null && isRed(u)){
  84. setBlack(p);//父节点设为黑色
  85. setBlack(u);//叔叔节点设为黑色
  86. setRed(g);//祖父节点设为红色
  87. current = g;//把祖父节点设为当前节点
  88. //继续向上平衡
  89. continue;
  90. }
  91. //情况2:当前节点为右节点,叔叔节点为黑色
  92. if (current == p.right){
  93. leftRotate(p);//父节点为支点左旋
  94. Entry<K,V> tmp = p;
  95. p = current;//父节点和当前节点互换
  96. current = tmp;//父节点设为当前节点
  97. }
  98. //情况3:当前节点为左节点,叔叔节点为黑色
  99. setBlack(p);//父节点设为黑色
  100. setRed(g);//祖父节点设为红色
  101. rightRotate(g);//祖父节点为支点右旋
  102. }else {//相反的操作
  103. u = g.left;
  104. if (u != null && isRed(u)){
  105. setBlack(p);
  106. setBlack(u);
  107. setRed(g);
  108. current = g;
  109. continue;
  110. }
  111. if (current == p.left){
  112. rightRotate(p);
  113. Entry<K,V> tmp = p;
  114. p = current;
  115. current = tmp;
  116. }
  117. setBlack(p);
  118. setRed(g);
  119. leftRotate(g);
  120. }
  121. }
  122. //最后将根节点设置为红色
  123. setBlack(root);
  124. }
  125.  
  126. public boolean containsKey(Object key){
  127. return getEntry(key) != null;
  128. }
  129.  
  130. public Set<Entry<K,V>> entrySet(){
  131. Set<Entry<K,V>> list = new HashSet<>(size + );
  132. entries(root,list);
  133. return list;
  134. }
  135.  
  136. private void entries(Entry<K,V> e,Set<Entry<K,V>> list){
  137. if (e != null){
  138. entries(e.left,list);
  139. list.add(e);
  140. entries(e.right,list);
  141. }
  142. }
  143.  
  144. public boolean containsValue(V v){
  145. return values().contains(v);
  146. }
  147.  
  148. public V get(Object key){
  149. Entry<K, V> entry = getEntry(key);
  150. return entry == null ? null : entry.getValue();
  151. }
  152.  
  153. private void setColor(Entry<K,V> e,boolean color){
  154. if (e != null) e.color = color;
  155. }
  156.  
  157. private void setRed(Entry<K,V> e){
  158. setColor(e,RED);
  159. }
  160.  
  161. private void setBlack(Entry<K,V> e){
  162. setColor(e,BLACK);
  163. }
  164.  
  165. private void setParent(Entry<K,V> e,Entry<K,V> p){
  166. if (e != null) e.parent = p;
  167. }
  168.  
  169. private boolean isBlack(Entry<K,V> e){
  170. return colorOf(e) == BLACK;
  171. }
  172.  
  173. private boolean isRed(Entry<K,V> e){
  174. return !isBlack(e);
  175. }
  176.  
  177. private Entry<K,V> parentOf(Entry<K,V> e){
  178. return e == null ? null : e.parent;
  179. }
  180.  
  181. private boolean colorOf(Entry<K,V> e){
  182. return e == null ? BLACK : e.color;
  183. }
  184.  
  185. /**
  186. * 右旋
  187. * @param e 旋转支点
  188. */
  189. private void rightRotate(Entry<K,V> e){
  190. //原支点的左节点
  191. Entry<K,V> left = e.left;
  192. //原支点的左节点的右节点
  193. Entry<K,V> leftOfRight = left.right;
  194. //新旧支点的替换
  195. left.parent = e.parent;
  196. if (e.parent == null){//支点的父节点为根节点的情况
  197. root = left;
  198. }else {//非跟节点
  199. if (e == e.parent.left)
  200. e.parent.left = left;
  201. else
  202. e.parent.right = left;
  203. }
  204. //将原支点变为新支点的右节点
  205. left.right = e;
  206. e.parent = left;
  207. //将新支点未旋转前的右节点变为转换后的原支点的左节点
  208. e.left = leftOfRight;
  209. if (leftOfRight != null)
  210. leftOfRight.parent = e;
  211. }
  212.  
  213. /**
  214. * 左旋
  215. * @param e 支点
  216. */
  217. private void leftRotate(Entry<K,V> e){
  218. //支点的右子节点
  219. Entry<K,V> right = e.right;
  220. //支点右子节点的左子节点
  221. Entry<K,V> rightOfLeft = right.left;
  222. //新旧支点的替换
  223. right.parent = e.parent;
  224. if (e.parent == null){
  225. root = right;
  226. }else {
  227. if (e == e.parent.left)
  228. e.parent.left = right;
  229. else
  230. e.parent.right = right;
  231. }
  232. //将原支点变为新支点的左节点
  233. right.left = e;
  234. e.parent = right;
  235. //将新支点的左节点变为就支点的右节点
  236. e.right = rightOfLeft;
  237. if (rightOfLeft != null)
  238. rightOfLeft.parent = e;
  239. }
  240.  
  241. public int getDeep(){
  242. return deep(root);
  243. }
  244.  
  245. private int deep(Entry<K,V> e){
  246. int deep = ;
  247. if (e != null){
  248. int leftDeep = deep(e.left);
  249. int rightDeep = deep(e.right);
  250. deep = leftDeep > rightDeep ? leftDeep + : rightDeep + ;
  251. }
  252. return deep;
  253. }
  254.  
  255. public V remove(Object key){
  256. if (key == null) return null;
  257. Entry<K,V> delEntry;
  258. delEntry = getEntry(key);
  259. if (delEntry == null) return null;
  260. size--;
  261. Entry<K,V> p = delEntry.parent;
  262. if (delEntry.right == null && delEntry.left == null){
  263. if (p == null){
  264. root = null;
  265. }else {
  266. if (p.left == delEntry){
  267. p.left = null;
  268. }else {
  269. p.right = null;
  270. }
  271. }
  272. }else if (delEntry.right == null){//只有左节点
  273. Entry<K,V> lc = delEntry.left;
  274. if (p == null) {
  275. lc.parent = null;
  276. root = lc;
  277. } else {
  278. if (delEntry == p.left){
  279. p.left = lc;
  280. }else {
  281. p.right = lc;
  282. }
  283. lc.parent = p;
  284. }
  285. }else if (delEntry.left == null){//只有右节点
  286. Entry<K,V> rc = delEntry.right;
  287. if (p == null) {
  288. rc.parent = null;
  289. root = rc;
  290. }else {
  291. if (delEntry == p.left)
  292. p.left = rc;
  293. else
  294. p.right = rc;
  295. rc.parent = p;
  296. }
  297. }else {//有两个节点,找到后继节点,将值赋给删除节点,然后将后继节点删除掉即可
  298. Entry<K,V> successor = successor(delEntry);//获取到后继节点
  299. boolean color = successor.color;
  300. V old = delEntry.value;
  301. delEntry.value = successor.value;
  302. delEntry.key = successor.key;
  303. if (delEntry.right == successor){//后继节点为右子节点,
  304. if (successor.right != null) {//右子节点有右子节点
  305. delEntry.right = successor.right;
  306. successor.right.parent = delEntry;
  307. }else {//右子节点没有子节点
  308. delEntry.right = null;
  309. }
  310. }else {
  311. successor.parent.left = null;
  312. }
  313. if (color == BLACK)
  314. //fixUpAfterRemove(child,parent);
  315. return old;
  316. }
  317. V old = delEntry.value;
  318. if (delEntry.color == BLACK)//删除为黑色时,需要重新平衡树
  319. if (delEntry.right != null)//删除节点的子节点只有右节点
  320. fixUpAfterRemove(delEntry.right,delEntry.parent);
  321. else if (delEntry.left != null)//删除节点只有左节点
  322. fixUpAfterRemove(delEntry.left,delEntry.parent);
  323. else
  324. fixUpAfterRemove(null,delEntry.parent);
  325. delEntry.parent = null;
  326. delEntry.left = null;
  327. delEntry.right = null;
  328. return old;
  329. }
  330.  
  331. private Entry<K, V> getEntry(Object key) {
  332. if (key == null) return null;
  333. Entry<K, V> delEntry = null;
  334. Entry<K, V> current = root;
  335. int ret;
  336. if (comparator == null){
  337. Comparable<K> k = (Comparable<K>) key;
  338. while (current != null){
  339. ret = k.compareTo(current.key);
  340. if (ret < )
  341. current = current.left;
  342. else if (ret > )
  343. current = current.right;
  344. else{
  345. delEntry = current;
  346. break;
  347. }
  348. }
  349. }else {
  350. for (;current != null;){
  351. ret = comparator.compare(current.key, (K) key);
  352. if (ret < )
  353. current = current.left;
  354. else if (ret > )
  355. current = current.right;
  356. else{
  357. delEntry = current;
  358. break;
  359. }
  360. }
  361. }
  362. return delEntry;
  363. }
  364.  
  365. //node表示待修正的节点,即后继节点的子节点(因为后继节点被挪到删除节点的位置去了)
  366. private void fixUpAfterRemove(Entry<K, V> node,Entry<K,V> parent) {
  367. Entry<K,V> other;
  368. while((node == null || isBlack(node)) && (node != root)) {
  369. if(parent.left == node) { //node是左子节点,下面else与这里的刚好相反
  370. other = parent.right; //node的兄弟节点
  371. if(isRed(other)) { //case1: node的兄弟节点other是红色的
  372. setBlack(other);
  373. setRed(parent);
  374. leftRotate(parent);
  375. other = parent.right;
  376. }
  377.  
  378. //case2: node的兄弟节点other是黑色的,且other的两个子节点也都是黑色的
  379. if((other.left == null || isBlack(other.left)) &&
  380. (other.right == null || isBlack(other.right))) {
  381. setRed(other);
  382. node = parent;
  383. parent = parentOf(node);
  384. } else {
  385. //case3: node的兄弟节点other是黑色的,且other的左子节点是红色,右子节点是黑色
  386. if(other.right == null || isBlack(other.right)) {
  387. setBlack(other.left);
  388. setRed(other);
  389. rightRotate(other);
  390. other = parent.right;
  391. }
  392.  
  393. //case4: node的兄弟节点other是黑色的,且other的右子节点是红色,左子节点任意颜色
  394. setColor(other, colorOf(parent));
  395. setBlack(parent);
  396. setBlack(other.right);
  397. leftRotate(parent);
  398. node = this.root;
  399. break;
  400. }
  401. } else { //与上面的对称
  402. other = parent.left;
  403.  
  404. if (isRed(other)) {
  405. // Case 1: node的兄弟other是红色的
  406. setBlack(other);
  407. setRed(parent);
  408. rightRotate(parent);
  409. other = parent.left;
  410. }
  411.  
  412. if ((other.left==null || isBlack(other.left)) &&
  413. (other.right==null || isBlack(other.right))) {
  414. // Case 2: node的兄弟other是黑色,且other的俩个子节点都是黑色的
  415. setRed(other);
  416. node = parent;
  417. parent = parentOf(node);
  418. } else {
  419.  
  420. if (other.left==null || isBlack(other.left)) {
  421. // Case 3: node的兄弟other是黑色的,并且other的左子节点是红色,右子节点为黑色。
  422. setBlack(other.right);
  423. setRed(other);
  424. leftRotate(other);
  425. other = parent.left;
  426. }
  427.  
  428. // Case 4: node的兄弟other是黑色的;并且other的左子节点是红色的,右子节点任意颜色
  429. setColor(other, colorOf(parent));
  430. setBlack(parent);
  431. setBlack(other.left);
  432. rightRotate(parent);
  433. node = this.root;
  434. break;
  435. }
  436. }
  437. }
  438. if (node!=null)
  439. setBlack(node);
  440. }
  441.  
  442. private Entry<K, V> successor(Entry<K, V> delEntry) {
  443. Entry<K,V> r = delEntry.right;//assert r != null;
  444. while (r.left != null){
  445. r = r.left;
  446. }
  447. return r;
  448. }
  449.  
  450. List<V> values(){
  451. List<V> set = new ArrayList<>(size+);
  452. midIterator(root,set);
  453. return set;
  454. }
  455.  
  456. private void midIterator(Entry<K,V> e, List<V> values){
  457. if (e != null){
  458. midIterator(e.left,values);
  459. values.add(e.value);
  460. midIterator(e.right,values);
  461. }
  462. }
  463.  
  464. public void clear(){
  465. clear(root);
  466. root = null;
  467. }
  468.  
  469. private void clear(Entry<K,V> node) {
  470. if (node != null){
  471. clear(node.left);
  472. node.left = null;
  473. clear(node.right);
  474. node.right = null;
  475. }
  476. }
  477.  
  478. public int size(){return size;}
  479.  
  480. static final class Entry<K,V>{
  481. private K key;
  482. private V value;
  483. private Entry<K,V> left;
  484. private Entry<K,V> right;
  485. private Entry<K,V> parent;
  486. private boolean color = BLACK;
  487. Entry(K key,V value,Entry<K,V> parent){
  488. this.key = key;
  489. this.value = value;
  490. this.parent = parent;
  491. }
  492. public K getKey() {
  493. return key;
  494. }
  495.  
  496. public V getValue() {
  497. return value;
  498. }
  499. }
  500.  
  501. }

  到此,红黑树的添加删除操作已经全部讲完了,如果文中有什么错误或不懂得地方,随时欢迎大家指出讨论。大家也可以关注公众号:【Java解忧杂货铺】,里面会不定时得发布一些技术干活,和学习视频。

基于Java实现红黑树的基本操作的更多相关文章

  1. Java实现红黑树

    转自:http://www.cnblogs.com/skywang12345/p/3624343.html 红黑树的介绍 红黑树(Red-Black Tree,简称R-B Tree),它一种特殊的二叉 ...

  2. Java数据结构——红黑树

    红黑树介绍红黑树(Red-Black Tree),它一种特殊的二叉查找树.执行查找.插入.删除等操作的时间复杂度为O(logn). 红黑树是特殊的二叉查找树,意味着它满足二叉查找树的特征:任意一个节点 ...

  3. 用Java实现红黑树

    红黑树是众多"平衡的"搜索树模式中的一种,在最坏情况下,它相关操作的时间复杂度为O(log n). 1.红黑树的属性 红黑树是一种二分查找树,与普通的二分查找树不同的一点是,红黑树 ...

  4. Java实现红黑树(平衡二叉树)

    前言 在实现红黑树之前,我们先来了解一下符号表. 符号表的描述借鉴了Algorithms第四版,详情在:https://algs4.cs.princeton.edu/home/ 符号表有时候被称为字典 ...

  5. Java 集合 | 红黑树 | 前置知识

    一.前言 0tnv1e.png 为啥要学红黑树吖? 因为笔者最近在赶项目的时候,不忘抽出时间来复习 Java 基础知识,现在准备看集合的源码啦啦.听闻,HashMap 在 jdk 1.8 的时候,底层 ...

  6. java数据结构——红黑树(R-B Tree)

    红黑树相比平衡二叉树(AVL)是一种弱平衡树,且具有以下特性: 1.每个节点非红即黑; 2.根节点是黑的; 3.每个叶节点(叶节点即树尾端NULL指针或NULL节点)都是黑的; 4.如图所示,如果一个 ...

  7. 红黑树(五)之 Java的实现

    概要 前面分别介绍红黑树的理论知识.红黑树的C语言和C++的实现.本章介绍红黑树的Java实现,若读者对红黑树的理论知识不熟悉,建立先学习红黑树的理论知识,再来学习本章.还是那句老话,红黑树的C/C+ ...

  8. 红黑树 Java实现

    概要 前面分别介绍红黑树的理论知识.红黑树的C语言和C++的实现.本章介绍红黑树的Java实现,若读者对红黑树的理论知识不熟悉,建立先学习红黑树的理论知识,再来学习本章.还是那句老话,红黑树的C/C+ ...

  9. Java 1.8 红黑树

    红黑树 R-B Tree R-B Tree,全称 Red-Black Tree 又称为 红黑树,它是一种特殊的二叉查找树,红黑树的每个节点都有存储位表示节点的颜色,可以是红Red 或者 黑Black ...

随机推荐

  1. Microsoft C++ 异常: std::system_error std::thread

    第一次使用std::thread,把之前项目里面的Windows的thread进行了替换,程序退出的然后发生了std::system_error. 经过调试,发现std::thread ,join了两 ...

  2. How to change from default to alternative Python version on Debian Linux

    https://linuxconfig.org/how-to-change-from-default-to-alternative-python-version-on-debian-linux You ...

  3. jsonp学习

    使用 JSONP 实现跨域通信:http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/

  4. Python中urllib.urlencode中文字符的一个问题

    Django项目在访问Restful service时调用urllib.urlencode编码中文字符串时碰到下面这个错误. v = quote_plus(str(v)) UnicodeEncodeE ...

  5. Java 代码重用:操作与上下文重用

    目录 操作重用 参数化操作 上下文重用 上下文作为模板方法 结束语 我几乎不需要讨论为什么重用代码是有利的.代码重用(通常)会导致更快的开发与更少的 BUG.一旦一段代码被封装和重用,那么检查程序是否 ...

  6. java之Hibernate框架实现数据库操作

    之前我们用一个java类连接MySQL数据库实现了数据库的增删改查操作---------MySQL篇: 但是数据库种类之多,除了MySQL,还有Access.Oracle.DB2等等,而且每种数据库语 ...

  7. php中获取用户登陆的IP地址以及常规处理

    本文为原创,转载请注明!  在我们开发多站点业务网站中,经常需要获取客户端的ip地址来给用户推荐其所在地址的信息的业务,用php获取客户端的ip地址,我们一般用到的PHP内置方法是$_SERVER[' ...

  8. Java接口和抽象类以及接口的意义,instanceof的利用

    接口interface: 1. 在接口中没有变量,成员无论如何定义,都是公共常量,public static final即使不显式声明也如此. 2. 所有接口方法均隐含public abstract即 ...

  9. Python 描述符是什么?以及如何实现

    先看一个例子,@property.被@property修饰的成员函数,将变为一个描述符.这是最简单的创建描述符的方式. class Foo: @property def attr(self): pri ...

  10. 使用伪类before和after

    .content { padding: 20px } .content::before { content: "我是before添加的内容"; font-weight: bold ...