算法导论 思考题 13.3-4(Treap树)

这篇博客介绍了如何使用C语言实现Treap树的数据结构,包括节点的旋转操作(左旋和右旋),Treap树的插入和删除方法,并提供了一个简单的示例展示如何在Treap树中查找、插入和删除节点。最后,还展示了前序遍历Treap树的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值