算法导论的伪代码的注释看的很晕啊,网上找到代码,研究下:
代码
void rb_tree_insert(rb_tree * &T, int value)
{
rb_tree *z = new rb_tree();
z->data = value;//即将插入的节点
rb_tree *y = nil;
rb_tree *x = T;
while (x != nil)
{
y = x;
if(x->data > z->data)
x = x->left;
else
x = x->right;
}
z->parent = y;
if(y == nil)
T = z;
else
{
if (z->data < y->data)
{
y->left = z;
}
else
{
y->right = z;
}
}
z->left = z->right = nil;
z->color = red;
}
rb_tree * rb_insert_fixup(rb_tree *T, rb_tree *z)
{
rb_tree *y = NULL;
while(z != T && z->parent->color == red)//z不是根节点而且父节点为红
{
if (z->parent == z->parent->parent->left)//父节点是祖父节点的左子树
{
y = z->parent->parent->left;//y为z的叔节点
if(y && y->color == red)//叔节点存在而且为红
{
z->parent->color = black;//更改父节点为黑
y->color = black;//叔节点也改为黑
z->parent->parent->color = red;//祖父节点改为红
z = z->parent->parent;//z上升至祖父节点继续迭代确保红黑树的性质
}
else //无叔节点或者叔节点为黑
{
if (z == z->parent->right)//如果新节点是父节点的右子树
{
z = z->parent;
left_rotate(z);
}
z->parent->color = black;//父节点改为黑色
z->parent->parent->color = red;//祖父节点改为红色
right_rotate(z->parent->parent);
}
}
else
{
y = z->parent->parent->right;//y为z的叔节点
if(y && y->color == red)//叔节点存在而且为红
{
z->parent->color = black;//更改父节点为黑
y->color = black;//叔节点也改为黑
z->parent->parent->color = red;//祖父节点改为红
z = z->parent->parent;//z上升至祖父节点继续迭代确保红黑树的性质
}
else //无叔节点或者叔节点为黑
{
if (z == z->parent->left)//如果新节点是父节点的右子树
{
z = z->parent;
right_rotate(z);
}
z->parent->color = black;//父节点改为黑色
z->parent->parent->color = red;//祖父节点改为红色
left_rotate(z->parent->parent);
}
}
}
T->color = black;
return T;
}