Implementation of red black tree

#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int data;
char color;
node *left,*right,*parent;
};
typedef node *nodeptr;
nodeptr root,par;
class aj
{
int i,j;
public:
void add(int x,nodeptr &);

void set(nodeptr );

nodeptr lr(nodeptr ,nodeptr );
nodeptr rr(nodeptr ,nodeptr );

void inorder(nodeptr );
};
void aj::set(nodeptr n)
{
if(n->parent==NULL)
n->color='b';
else if(n->parent->color=='b')
return;
else
{
nodeptr u,d,p=n->parent;
d=n->parent->parent;
if(p==d->left)
u=d->right;
else
u=d->left;
if(u!=NULL&&u->color=='r')
{
p->color='b';
u->color='b';
d->color='r';
set(d);
}
else
{
if(n==p->right&&p==d->left)
{
p=lr(p,n);
n=n->left;
}
else if(n==p->left&&p==d->right)
{
p=rr(p,n);
n=n->right;
}
p=n->parent;//not required
p->color='b';
d->color='r';
if(n==p->left)
d=rr(d,d->left);
else
d=lr(d,d->right);
}
}
}
void aj::inorder(nodeptr p)
{
if(p!=NULL)
{
inorder(p->left);
cout<<endl<<p->data<<" "<<p->color;
inorder(p->right);
}
}
nodeptr aj::rr(nodeptr p,nodeptr q)
{
nodeptr r=p;
p->left=q->right;
if(q->right!=NULL)
q->right->parent=p;
q->right=p;
q->parent=p->parent;
p->parent=q;
if(q->parent!=NULL)
{
if(q->data<q->parent->data)
q->parent->left=q;
else
q->parent->right=q;
}
if(r==root)
root=q;
return q;
}
nodeptr aj::lr(nodeptr p,nodeptr q)
{
nodeptr r=p;
p->right=q->left;
if(q->left!=NULL)
q->left->parent=p;
q->left=p;
q->parent=p->parent;
p->parent=q;
if(q->parent!=NULL)
{
if(q->data<q->parent->data)
q->parent->left=q;
else
q->parent->right=q;
}
if(r==root)
root=q;
return q;
}
void aj::add(int x,nodeptr &n)
{
if(n==NULL)
{
n=new node;
n->data=x;
n->left=NULL;
n->right=NULL;
n->color='r';
n->parent=par;
set(n);
}
else if(x<n->data)
{
par=n;
add(x,n->left);
}
else if(x>n->data)
{
par=n;
add(x,n->right);
}
else
cout<<"\nData exist";
}
int main()
{
root=par=NULL;
aj a;
a.add(20,root);
a.add(10,root);
a.add(16,root);
a.add(17,root);
a.add(19,root);
a.inorder(root);
system("pause");
return 0;
}

How to implement it using black height concept.. is any pseudocode or algo available
Topic archived. No new replies allowed.