答案 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