treap树及相关算法

时间:2023-01-26 03:37:37

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct treenode
{
int key;
int priority;
int flag;
treenode* parent;
treenode* lchild;
treenode* rchild; }node,*pnode;
pnode treeroot=NULL;
void adjusttree(pnode p)
{ if(p->parent==NULL)return;
if(p->priority>=p->parent->priority)return;
if(p->flag==)//p lie in the left subtree, rotate right
{
pnode prt=p->parent,rchild=p->rchild;
if(p->parent->flag==)
{
prt->lchild=rchild;
if(rchild)rchild->parent=prt;
if(rchild)rchild->flag=;
p->rchild=prt;
prt->parent=p;
prt->flag=;
treeroot=p;
p->parent=NULL;
p->flag=;
return;
}
else if(p->parent->flag==)
{
pnode grdp=prt->parent;
prt->lchild=rchild;
if(rchild)rchild->parent=prt;
if(rchild)rchild->flag=;
p->rchild=prt;
prt->parent=p;
prt->flag=;
grdp->lchild=p;
p->parent=grdp;
p->flag=;
adjusttree(p);
}
else if(p->parent->flag==)
{
pnode grdp=prt->parent;
prt->lchild=rchild;
if(rchild)
rchild->parent=prt;
if(rchild)
rchild->flag=;
p->rchild=prt;
prt->parent=p;
prt->flag=;
grdp->rchild=p;
p->parent=grdp;
p->flag=;
adjusttree(p);
} }
else if(p->flag==)//p lie in the right tree, rotate left
{
pnode prt=p->parent,lchild=p->lchild;
if(p->parent->flag==)
{
prt->rchild=lchild;
if(lchild)lchild->parent=prt;
if(lchild)lchild->flag=;
p->lchild=prt;
prt->parent=p;
prt->flag=;
treeroot=p;
p->parent=NULL;
p->flag=;
return; }
else if(p->parent->flag==)
{
pnode grdp=prt->parent;
prt->rchild=lchild;
if(lchild)lchild->parent=prt;
if(lchild)lchild->flag=;
p->lchild=prt;
prt->parent=p;
prt->flag=;
grdp->lchild=p;
p->parent=grdp;
p->flag=;
adjusttree(p);
}
else if(p->parent->flag==)
{
pnode grdp=prt->parent;
prt->rchild=lchild;
if(lchild)lchild->parent=prt;
if(lchild)lchild->flag=;
p->lchild=prt;
prt->parent=p;
prt->flag=;
grdp->rchild=p;
p->parent=grdp;
p->flag=;
adjusttree(p);
} } }
void insert_node(pnode root,pnode p,pnode parent,int flag)
{
if(root==NULL)
{
p->flag=flag;
p->parent=parent;
if(flag==)parent->lchild=p;
if(flag==)parent->rchild=p;
if(p->priority<p->parent->priority)adjusttree(p);
return;
}
if(root->key>=p->key)insert_node(root->lchild,p,root,);
else insert_node(root->rchild,p,root,);
}
pnode createnode(int key,int priority)
{
pnode tmp;
tmp=(pnode)malloc(sizeof(node));
tmp->flag=;
tmp->parent=NULL;
tmp->rchild=NULL;
tmp->lchild=NULL;
tmp->key=key;
tmp->priority=priority;
return tmp;
}
void dsptree(pnode p)
{
if(p)dsptree(p->lchild);
if(p){printf("#%dsubtree key=%d\n",p->flag,p->key);}
if(p)dsptree(p->rchild);
}
int main()
{
treeroot=createnode(,);
pnode n1=createnode(,);
pnode n2=createnode(,);
pnode n3=createnode(,);
pnode n4=createnode(,);
insert_node(treeroot,n1,,);
insert_node(treeroot,n2,,);
insert_node(treeroot,n3,,);
insert_node(treeroot,n4,,);
dsptree(treeroot);
system("pause");
return ;
}