当父母P是红色但叔叔U是黑色时插入红黑树

时间:2018-12-15 12:02:09

标签: data-structures red-black-tree

在红黑树中插入节点时,这是wiki中的情况4。

正如picture所示,节点“ U”似乎不是NIL,因为它具有chlidren。

但这是一棵红黑的树吗?

图片有误还是我错过了什么?

1 个答案:

答案 0 :(得分:0)

  

但这是一棵红黑的树吗?

不。这是插入节点后的一棵红黑树,在本例中为N。这是修复该树的所有步骤,因此再次成为一棵红黑树。

图片没错。

发生插入时,新节点将在底部,即叶节点,通常为红色。修复过程将针对根进行(并保证可以进行工作)。

用这样的伪算法术语来说,算法是

LOOP
   P = PARENT(N)
   IF P == NULL THEN
      'N MUST BE ROOT
      N.COLOUR = BLACK
      RETURN
   ENDIF
   IF P.COLOUR == BLACK THEN
      'FIXUPS HAVE ENDED
      RETURN
   ENDIF
   'NOTE: SINCE PARENT IS RED AND PREVIOUSLY WAS A RED-BLACK TREE THEN
   'GRANDPARENT EXISTS AND MUST BE BLACK AS ROOT NODE IS BLACK
   G = GRANDPARENT(N)
   U = UNCLE(N)
   IF U.COLOUR = RED THEN
       'COLOUR FLIP. BLACK NODE HEIGHT DOES NOT CHANGE
       P.COLOUR = BLACK
       U.COLOUR = BLACK
       G.COLOUR = RED
       'BUT G's PARENT COULD BE RED, SO LOOP AGAIN WITH NEW N BEING G
       N = G
    ELSE
       'PARENT IS RED AND UNCLE IS BLACK
       IF N IS ON INSIDE UNDERNEATH G
           ROTATE OUTWARDS ABOUT P
           N = P
       END IF
       'N IS ON OUTSIDE
       ROTATE ABOUT G TOWARD U
       P.COLOUR = BLACK 'NEW GRANDFATHER
       G.COLOUR = RED   'NEW UNCLE
       'N.COLOUR = RED  'NO CHANGE
       RETURN
    END IF


ENDLOOP