#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
char colour;
struct node *parent;
struct node *left_child;
struct node *right_child;
};
struct node* root=NULL;
void visit(struct node* p);
void pre_fix_tour(struct node* p);
void left_rotate(struct node *x)
{
struct node *y;
y=x->right_child;
x->right_child=y->left_child;
if(y->left_child!=NULL)
y->left_child->parent = x;
y->parent = x->parent;
if(x->parent==NULL)
root = y;
else if(x == x->parent->left_child)
x->parent->left_child = y;
else
x->parent->right_child = y;
y->left_child = x;
x->parent = y;
}
void right_rotate(struct node *y)
{
struct node *x;
x = y->left_child;
y->left_child = x->right_child;
if (x->right_child != NULL)
x->right_child->parent = y;
x->parent = y->parent;
if(y->parent == NULL)
root = x;
else if(y == y->parent->left_child)
y->parent->left_child = x;
else
y->parent->right_child = x;
x->right_child = y;
y->parent = x;
}
void re_balance(struct node *z)
{
struct node *y;
while ((z->parent!=NULL)&&(z->parent->colour == 'R'))
{
if (z->parent == z->parent->parent->left_child)
{
y = z->parent->parent->right_child;
if ((y!= NULL)&&(y->colour == 'R'))
{
z->parent->colour = 'B';
y->colour = 'B';
z->parent->parent->colour = 'R';
z = z->parent->parent;
}
else
{
if (z == z->parent->right_child)
{
z = z->parent;
left_rotate(z);
}
z->parent->colour = 'B';
z->parent->parent->colour = 'R';
right_rotate(z->parent->parent);
}
}
else
{
y = z->parent->parent->left_child;
if ((y!= NULL)&&(y->colour == 'R'))
{
z->parent->colour = 'B';
y->colour = 'B';
z->parent->parent->colour = 'R';
z = z->parent->parent;
}
else
{
if (z == z->parent->left_child)
{
z = z->parent;
right_rotate(z);
}
z->parent->colour = 'B';
z->parent->parent->colour = 'R';
left_rotate(z->parent->parent);
}
}
}
root->colour='B';
}
void insert(int data)
{
struct node
*z
=(struct node
*)malloc(sizeof(struct node
)); z->data=data;
z->left_child=NULL;
z->right_child=NULL;
z->colour = 'R';
struct node *x=root;
struct node *y=NULL;
if (x == NULL )
{
root = z;
root->colour = 'B';
return;
}
while (x!= NULL)
{
y = x;
if (z->data < x->data)
x = x->left_child;
else
x = x->right_child;
}
z->parent = y;
if (y == NULL)
root = z;
else if(z->data < y->data)
y->left_child = z;
else
y->right_child = z;
z->left_child = NULL;
z->right_child = NULL;
z->colour = 'R';
re_balance(z);
}
void pre_fix_tour(struct node* p)
{
if(p==NULL)
return ;
else
visit(p);
}
void visit(struct node* p)
{
pre_fix_tour(p->left_child);
if (p->parent==NULL)
printf("%d %c NIL \n",p
->data
,p
->colour
);
else
printf("%d %c %d \n",p
->data
,p
->colour
,p
->parent
->data
);
pre_fix_tour(p->right_child);
}
int main()
{
int n;
int i,a_i;
for(i=0;i<n;i++)
{
insert(a_i);
}
pre_fix_tour(root);
return 0;
}