性质(5个)
- 每个结点不是红色就是黑色
- 根结点黑色
- 每个叶子结点(NIL)黑色
- 每个红色结点有两个黑色的子结点
- 每个结点到其后代所有叶子结点的 简单路径 上,包含相同数目的黑色结点
伪代码
1.
left-rotate(T,x) //x.right!=NULL
//when connecting parent and child, first set parent -> child (parent.l/r=child) , then child -> parent (child.p=parent)
y=x.right
x.right=y.left
if x.right!=NULL
x.right.p=x
y.p=x.p
//check whether x is root--! using T.root.p=T.nil !
if x.p==T.nil
T.root=y
//remember to link y to x.p
else if x.p.left=x
x.p.left=y
else
x.p.right=y
y.left=x
x.p=y
2.
right-rotate(T,x) //x.left!=NULL
y=x.left
x.left=y.right
if x.left!=NULL
x.left.p=x
y.p=x.p
//!!!here
if x.p.right==x
x.p.right=y
else
x.p.left=y
y.right=x
x.p=y
/**
*RB-insert 与 tree-insert 有四处不同:1.NIL用T.nil代替 2.置z.left & z.right 为T.nli 3.着z为红色 4.RE-insert-fixup
**/
3.
RB-insert(T,z)
if T.root==T.nil // T.nil
z.p=T.nil
T.root=z
else
x=T.root
while x!=NULL
y=x
if z.key<x.key
x=x.left
else
x=x.right
if z.key<y.key
y.left=z
else
y.right=z
z.p=y
z.left=T.nil
z.right=T.nil
z.color=red
RB-insert-fixup(T,z)
4.(待验证)
RB-insert-fixup(T,z)
while z.p.color==red
if z.p==z.p.p.left
if z.p.p.right.color==red
z.p.p.right.color=black
z.p.color=black
z.p.p.color=red
z=z.p.p
else
if z==z.p.right
z=z.p
left-rotate(T,z)
else
//paint first, then rotate
z.p.color=black
z.p.p.color=red
right-rotate(T,z.p.p)
else
if z.p.p.left.color==red
z.p.color=black
z.p.p.left.color=black
z.p.p.color=red
z=z.p.p
else
if z==z.p.left
z=z.p
right-rotate(T,z)
else
z.p.p.color=red
z.p.color=black
left-rotate(T,z.p.p)
5.
RB-transplant(T,u,v)
if u.p==T.nil
T.root=v
else if u.p.left==u // here use else if , otherwise if u.p==T.nil , u.p.left has no meaning
u.p.left=v
else
u.p.right=v
v.p=u.p
6.
RB-delete(T,z)
y-origin-color=z.color
if z.right==T.nil
x=z.left
RB-transplant(T,z,x)
else if z.left==T.nil
x=z.right
RB-transplant(T,z,x)
else
y=tree-minimum(z.right)
y-origin-color=y.color
if y.p!=z
RB-transplant(T,y,x)
//!
y.right=z.right
y.right.p=y
RB-transplant(T,z,y)
y.left=z.left
y.left.p=y
//!y.color may change! the color stay the same in this z's position?
y.color=z.color
if y-origin-color==black
RB-delete-fixup(T,x)
7.
RB-delete-fixup(T,x)
while x!=T.root and x.color==black
if x.p.left==x
w=x.p.right
if w.color==red
w.color=black
x.p.color=red
left-rotate(T,x.p)
else
if w.left.color==black and w.right.color==black
w.color=red
x=x.p
else if w.right.color==red
w.right.color=black
w.color=x.p.color //!! x.p can be black / red
x.p.color=black
left-rotate(T,x.p)
//!!!! all set
x=T.root
else
w.left.color=black
w.color=red
right-rotate(T,w)
else (same but exchanged "right" and "left") // will be completed later