Treap模板

Treap,又称树堆,是一个随机附加域满足堆性质的二叉搜索树,其结构相当于随机数据插入的二叉搜索树。其基本的期望时间复杂度为O(logn)。相对于其他的平衡二叉搜索树,Treap的特点是实现简单,且能基本实现随机平衡结构。
Treap的作用是:它的作用同BST一样,引入优先级的概念是为了防止BST退化成一个链表,其他的查找复杂度为O(n),当然可以完全随机的插入节点,但是有时候并不知道所有的节点,这种情况下可以采用Treap,即当需要插入一个新的key的值时,可以随机的生成一个优先级(fix)约束Treap,从而达到随机生成BST 的目的。

#include<cstdio>
#include <cstring>
#include <cstdlib>
#include <time.h>
#include <iostream>
using namespace std;
struct Treap_Node
{
    Treap_Node *left,*right;
    int val,fix;//关键值,随机优先值
};
void Treap_Left_Rotate(Treap_Node * &a)
{
    Treap_Node *b=a->right;
    a->right=b->left;
    b->left=a;
    a=b;
}
void Treap_Right_Rotate(Treap_Node *&a)
{
    Treap_Node * b=a->left;
    a->left=b->right;
    b->right=a;
    a=b;
}
void Treap_Insert(Treap_Node *&p,int val)
{
    if(!p)
    {
        p=(Treap_Node*)malloc(sizeof (Treap_Node));
        if(p==NULL)
            exit(1);
        p->val=val;
        p->fix=rand();
        p->left=p->right=NULL;
    }
    else if(val<=p->val)
    {
        Treap_Insert(p->left,val);
        if(p->left->fix<p->fix)
            Treap_Right_Rotate(p);
    }
    else
    {
        Treap_Insert(p->right,val);
        if(p->right->fix<p->fix)
            Treap_Left_Rotate(p);
    }

}
void Treap_Delete(Treap_Node *&p,int val)
{
    if(val==p->val)
    {
        Treap_Node *t=p;
        if(!p->right)
        {
            p=p->left;
            delete t;
        }

        else if(!p->left)
        {
            p=p->right;
             delete t;
        }

        else
        {
            if(p->left->fix<p->right->fix)
            {
                Treap_Right_Rotate(p);
                Treap_Delete(p->right,val);
            }
            else
            {
                Treap_Left_Rotate(p);
                Treap_Delete(p->left,val);
            }
        }
    }
    else if(val<p->val)
        Treap_Delete(p->left,val);
    else
        Treap_Delete(p->right,val);
}
void PrintTree(Treap_Node *p)
{
    if(p)
    {
        PrintTree(p->left);
        printf("%d %d\n",p->val,p->fix);
        PrintTree(p->right);
    }
}
int main()
{
    Treap_Node *root=NULL;
    srand((unsigned int)time(NULL));
    for(int i=0; i<100; i++)
    {
        Treap_Insert(root,i);
    }
    cout<<"Print tree"<<endl;
    PrintTree(root);
    for(int i=0; i<100; i++)
    {
        Treap_Delete(root,i);
    }
    cout<<"Print Tree After Delete:"<<endl;
    PrintTree(root);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值