I am trying to insert nodes in red black trees. The functions rotate_left, rotate_right, insertion are correct but rb_fixup seems to be wrong. The red color is shown as 1 and black as 0. I have implemented algo from CLRS. When third element is inserted it gives a segmentation fault. The code of rb_fixup is:
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;
}
I solved the above problem. The error with the above code is that it if the uncle is red, it does color the uncle and parent black and the grandparent red but it then goes down to do the operations written after
else if
of each condition and many conditions were not done correctly. The final code looks like the following:-