#include <stdio.h>
#include <stdlib.h>
typedef struct TTNode
{
int key;
int priority;
TTNode *p;
TTNode *left;
TTNode *right;
}TT,*pTT;
void leftRotate(pTT *root,pTT x)
{
if(x)
{
if(!x->right)
return;
pTT y=x->right;
y->p=x->p;
if(x->p==NULL)
*root=y;
else if(x==x->p->left)
x->p->left=y;
else
x->p->right=y;
x->right=y->left;
y->left=x;
x->p=y;
}
}
void rightRotate(pTT *root,pTT y)
{
if(y)
{
if(!y->left)
return;
pTT x=y->left;
x->p=y->p;
if(y->p==NULL)
*root=x;
else if(y==y->p->left)
y->p->left=x;
else
y->p->right=x;
y->left=x->right;
x->right=y;
y->p=x;
}
}
pTT newNode(int key,int priority)
{
pTT z=(pTT)malloc(sizeof(TT));
z->key=key;
z->left=NULL;
z->p=NULL;
z->priority=priority;
z->right=NULL;
return z;
}
void swop(pTT *x,pTT *y)
{
pTT *temp=x;
x=y;
x=temp;
}
void TTinsert(pTT *root,int key,int priority)
{
pTT z=newNode(key,priority),x=*root,y=NULL;
if(!x)
{
*root=z;
return;
}
while(x)
{
y=x;
if(z->key<=x->key)
x=x->left;
else
x=x->right;
}
z->p=y;
if(z->key<=y->key)
{
y->left=z;
}
else
{
y->right=z;
}
while(y)
{
if(z==y->left)
{
if(y->priority>z->priority)
{
rightRotate(root,y);
y=z->p;
}
else
break;
}
else
{
if(y->priority>z->priority)
{
leftRotate(root,y);
y=z->p;
}
else
break;
}
}
}
bool TTdelete(pTT *root,pTT x)
{
if(x==NULL)
return false;
while(x->left && x->right)
{
if(x->left->priority<=x->right->priority)
{
rightRotate(root,x);
}
else
{
leftRotate(root,x);
}
}
if(x->left)
{
x->left->p=x->p;
if(x->p==NULL)
*root=x->left;
else if(x==x->p->left)
x->p->left=x->left;
else
x->p->right=x->left;
}
else
{
if(x->p==NULL)
*root=x->right;
else if(x==x->p->left)
x->p->left=x->right;
else
x->p->right=x->right;
}
}
pTT treeSearch(pTT root,int key)
{
pTT x=root;
while(x)
{
if(x->key==key)
return x;
if(key<x->key)
x=x->left;
else
x=x->right;
}
return x;
}
void preTrav(pTT root,char c)
{
if(!root)
return;
printf("key=%d,pri=%d,%c\n",root->key,root->priority,c);
preTrav(root->left,'L');
preTrav(root->right,'R');
}
void main()
{
pTT root=NULL;
TTinsert(&root,11,6);
TTinsert(&root,7,13);
TTinsert(&root,17,12);
TTinsert(&root,3,18);
TTinsert(&root,9,22);
TTinsert(&root,14,14);
TTinsert(&root,18,20);
TTinsert(&root,16,26);
TTinsert(&root,15,30);
//preTrav(root,'M');
pTT x=treeSearch(root,11);
TTdelete(&root,x);
preTrav(root,'M');
getchar();
}
算法导论 思考题 13.3-4(Treap树)
最新推荐文章于 2024-05-01 01:51:49 发布