红黑树


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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值