const bool RED = true;
const bool BLACK = false;
struct Node
{
int num;
Node* left;
Node* right;
bool color;
int N;
Node(int v)
{
num = v;
left = right = NULL;
color = RED;
N = 1;
}
};
class RBTree
{
public:
RBTree()
{
root = NULL;
}
void AddNode(int v)
{
root = AddNode(root,v);
}
int Rank(int v)
{
return Rank(root,v);
}
int RangeSearch(int lo,int hi)
{
cnt = 0;
RangeSearch(root,lo,hi);
return cnt;
}
void print()
{
print(root);
}
private:
Node* root;
int cnt;
Node* AddNode(Node* x,int v)
{
if (x == NULL)
return new Node(v);
int cmp = x->num - v;
if(cmp>0)
x->left = AddNode(x->left,v);
else if(cmp<0) x->right = AddNode(x->right,v);
else x->num = v;
if(isRed(x->right)&&!isRed(x->left)) x = rotateLeft(x);
if(isRed(x->left)&&isRed(x->left->left)) x = rotateRight(x);
if(isRed(x->left)&&isRed(x->right)) flipColors(x);
x->N = Size(x->left) + Size(x->right) + 1;
return x;
}
int Rank(Node* x,int v)
{
if(x == NULL) return 0;
int cmp = x->num - v;
if(cmp>0) return Rank(x->left,v);
else if (cmp<0) 1+ Size(x->left) + Rank(x->right,v);
else return Size(x->left);
}
void RangeSearch(Node* x,int lo,int hi)
{
if(x == NULL ) return;
int cmplo = lo - x->num;
int cmphi = hi - x->num;
if(cmplo>0) RangeSearch(x->right,lo,hi);
if(cmplo<=0&&cmphi>=0)
{
cnt++;
RangeSearch(x->left,lo,hi);
RangeSearch(x->right,lo,hi);
}
if(cmphi<0) RangeSearch(x->left,lo,hi);
}
void print(Node*x)
{
if(x == NULL ) return ;
print(x->left);
cout<<" "<<x->num<<" ";
print(x->right);
}
Node* rotateLeft(Node* h)
{
Node* x = h->right;
h->right = x->left;
x->left = h;
x->color = h->color;
h->color = RED;
return x;
}
Node* rotateRight(Node* h)
{
Node* x = h->left;
h->left = x->right;
x->right = h;
x->color = h->color;
h->color = RED;
return x;
}
Node* flipColors(Node* h)
{
h->left->color = BLACK;
h->right->color = BLACK;
h->color = RED;
}
bool isRed(Node* x)
{
if(x == NULL) return false;
return x->color == RED;
}
int Size(Node* x)
{
if(x == NULL) return 0;
else return x->N;
}
};
红黑树
最新推荐文章于 2024-06-20 12:03:06 发布