BST - treap

Posted dy blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BST - treap相关的知识,希望对你有一定的参考价值。

#include<cstdio>
#include<cstdlib>
using namespace std;
struct treapNode {
    int val,ra;
    treapNode *left,*right;
};

void rightRoate(treapNode *&root) {
    treapNode *right = root->right;
    root->right = right->left;
    right->left = root;
    root = right;
}

void leftRoate(treapNode *&root) {
    treapNode *left = root->left;
    root->left = left->right;
    left->right = root;
    root = left;
}

void insert(treapNode *&root,int val) {
    if(!root) {
        root = new treapNode;
        root->val = val;
        root->ra = rand()*rand();
        root->left = root->right = NULL;
        return;
    }
    if(val <= root->val) {
        insert(root->left,val);
        if(root->ra > root->left->ra) {
            leftRoate(root);
        }
    }
    else {
        insert(root->right,val);
        if(root->ra > root->right->ra) {
            rightRoate(root);
        }
    }
}

treapNode** find(treapNode *&root,int val) {
    if(!root) {
        return NULL;
    }
    if(val == root->val) {
        return &root;
    } else if(val < root->val) {
        return find(root->left,val);
    } else {
        return find(root->right,val);
    }
}

void erase(treapNode *&root) {
    if(!root->left) {
        treapNode* tmp = root;
        root = root->right;
        delete tmp;
        return;
    } 
    if(!root->right) {
        treapNode *tmp = root;
        root = root->left;
        delete tmp;
        return;
    }
    if(root->left->ra > root->right->ra) {
        rightRoate(root);
        erase(root->left);
    } else {
        leftRoate(root);
        erase(root->right);
    }
}


void destroyTreap(treapNode *&root,bool &first) {
    if(!root) {
        return;
    }
    destroyTreap(root->left,first);
    if(!first) printf(" ");
    printf("%d",root->val);
    first = false;
    destroyTreap(root->right,first);
    //root->left = root->right = NULL;
    //delete root;
}

int main() {
    int n;
    treapNode*root;
    while(scanf("%d",&n)==1) {
        root = NULL;
        for(int i=0,x;i<n;i++) {
            scanf("%d",&x);
            insert(root,x);
        }
        bool first = true;
        destroyTreap(root,first);
        printf("\n");
        for(int x;scanf("%d",&x) == 1;) {
            treapNode **tmp = find(root,x);
            if(!tmp) {
                printf("not exist\n");
                continue;
            }
            printf("find %d\n",(*tmp)->val);
            erase(*tmp);
            destroyTreap(root,first);
            printf("\n");
        }
    }
}

 

以上是关于BST - treap的主要内容,如果未能解决你的问题,请参考以下文章

Treap 实现名次树

BST - treap

Treap(树堆)详解

Treap(树堆)详解

可持久化Treap(fhq Treap,非旋转式Treap)学习(未完待续)

重量平衡树之Treap:以随机优先级来维护堆结构,并满足BST性质