c - Error in inserting nodes in red black trees -
i trying insert nodes in red black trees. functions rotate_left, rotate_right, insertion correct rb_fixup seems wrong. red color shown 1 , black 0. have implemented algo clrs. when third element inserted gives segmentation fault. 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 above problem. error above code if uncle red, color uncle , parent black , grandparent red goes down operations written after else if
of each condition , many conditions not done correctly. final code looks following:-
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; }
Comments
Post a Comment