我正在尝试在红黑树中插入节点。函数rotate_left,rotate_right,插入是正确的,但rb_fixup似乎是错误的。红色显示为1,黑色显示为0.我已经实现了CLRS的算法。当插入第三个元素时,它会产生分段错误。 rb_fixup的代码是:
struct node
{
int data;
int color;
struct node *left;
struct node *right;
struct node *parent;
}*root;
rb_fixup(struct node *z)
{
struct node *y;
y=(struct node *)malloc(sizeof(struct node));
while(z->parent->color==1)
{
if(z->parent==z->parent->parent->left)
{
y=z->parent->parent->right;
if(y->color==1)
{
z->parent->color=0;
y->color=0;
z->parent->parent->color=1;
z=z->parent->parent;
}
else if(z==z->parent->right)
{
z=z->parent;
rotate_left(z);
}
z->parent->color=0;
z->parent->parent->color=1;
rotate_right(z->parent->parent);
}
else if(z->parent==z->parent->parent->right)
{
y=z->parent->parent->left;
if(y->color==1)
{
z->parent->color=0;
y->color=0;
z->parent->parent->color=1;
z=z->parent->parent;
}
else if(z->parent->left==z)
{
z=z->parent;
rotate_right(z);
}
z->parent->color=0;
z->parent->parent->color=1;
rotate_left(z->parent->parent);
}
}
root->color=0;
}
答案 0 :(得分:0)
我解决了上述问题。上面代码的错误是,如果叔叔是红色的,它会为叔叔和父母黑色和祖父母红色着色但是然后它会在每个条件的else if
之后执行写操作,并且许多条件是做得不对。最终代码如下所示: -
rb_fixup(struct node *z)
{
struct node *y;
y=(struct node *)malloc(sizeof(struct node));
while(z->parent->color==1 && z->parent!=NULL)
{
if(z->parent==z->parent->parent->left)
{
if(z->parent->parent->right!=NULL)
y=z->parent->parent->right;
if(y->color==1)
{
z->parent->color=0;
y->color=0;
z->parent->parent->color=1;
z=z->parent->parent;
}
else if(z==z->parent->right)
{
z=z->parent;
rotate_left(z,z->right);
z->parent->color=0;
z->parent->parent->color=1;
rotate_right(z->parent->parent,z->parent);
}
else
{
z->parent->color=0;
z->parent->parent->color=1;
rotate_right(z->parent->parent,z->parent);
}
}
else
{
if(z->parent->parent->left!=NULL)
{
y=z->parent->parent->left;
}
if(y->color==1)
{
z->parent->color=0;
y->color=0;
z->parent->parent->color=1;
z=z->parent->parent;
}
else if(z==z->parent->left)
{
z=z->parent;
rotate_right(z,z->left);
z->parent->color=0;
z->parent->parent->color=1;
rotate_left(z->parent->parent,z->parent);
}
else
{
z->parent->color=0;
z->parent->parent->color=1;
rotate_left(z->parent->parent,z->parent);
}
}
}
root->color=0;
}