#include<bits/stdc++.h>
using namespace std;
typedef struct node Node;
typedef struct treap_t Treap;
typedef Node* nodePoint;
struct node{
int key; //关键字
int priority; //随机优先级
Node* left; //左节点
Node* right; //右节点
};
Node* root;//Treap的根结点
void rotate_left(Node* &node) {//左旋转
Node* x = node->right;
node->right = x->left;
x->left =node;
node = x;
}
void rotate_right(Node* &node) { //右旋转
Node* x = node->left;
node->left = x->right;
x->right = node;
node = x;
}
void treap_insert(Node* &root, int key, int priority) { //插入操作
//根为NULL,则直接创建此结点为根结点
if (root == NULL) {
root = (Node*)new Node;
root->left = NULL;
root->right = NULL;
root->priority = priority;
root->key = key;
}
else if (key <root->key) {//向右插入结点
treap_insert(root->left, key, priority);
if (root->left->priority < root->priority)rotate_right(root);
}
else { //向左插入结点
treap_insert(root->right, key, priority);
if (root->right->priority < root->priority)rotate_left(root);
}
}
void treap_delete(Node* &root, int key) { //删除结点操作
if (root != NULL){
if (key < root->key)treap_delete(root->left, key);
else if (key > root->key)treap_delete(root->right, key);
else{
if (root->left == NULL)root = root->right;//左孩子为空
else if (root->right == NULL)root = root->left;//右孩子为空
else{//左右孩子均不为空
if (root->left->priority < root->right->priority){//先旋转,然后再删除
rotate_right(root);
treap_delete(root->right, key);
}
else{
rotate_left(root);
treap_delete(root->left,key);
}
}
}
}
}
void in_order_traverse(Node* root){ //中序遍历
if (root!= NULL) {
in_order_traverse(root->left);
printf("%d\t", root->key);
in_order_traverse(root->right);
}
}
int depth(Node* node){ //计算树的高度
if(node == NULL) return -1;
int l = depth(node->left);
int r = depth(node->right);
return (l < r)?(r+1):(l+1);
}
int main(){
srand(time(0));
for (int i = 0; i < 10; i++) { //插十个数
int pri=rand();
printf("key:%d priority:%d\n",i,pri);
treap_insert(root,i,pri);
}
int rmKey;scanf("%d",&rmKey); //删除键值
treap_delete(root, rmKey);
in_order_traverse(root); //中序遍历
printf("\nTreap高度:%d\n", depth(root)); //求树堆高度
return 0;
}
树堆treap
猜你喜欢
转载自blog.csdn.net/cj1064789374/article/details/85379829
今日推荐
周排行