给出Treap的完整代码
时间: 2023-02-07 15:13:09 浏览: 127
Treap 是一种随机化的二叉搜索树数据结构,它结合了二叉搜索树的有序性和堆的随机性。其中,每个节点都有一个优先级(priority),并保证了在树中任意两个节点的优先级都是独立随机生成的。
以下是 Treap 的完整代码(使用 C++ 语言):
```cpp
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key, priority;
Node *left, *right;
Node(int key, int priority) : key(key), priority(priority), left(NULL), right(NULL) {}
};
class Treap {
Node *root;
void rotateRight(Node *&p) {
Node *q = p->left;
p->left = q->right;
q->right = p;
p = q;
}
void rotateLeft(Node *&p) {
Node *q = p->right;
p->right = q->left;
q->left = p;
p = q;
}
void insertUtil(Node *&p, int key, int priority) {
if (!p) {
p = new Node(key, priority);
return;
}
if (key < p->key) {
insertUtil(p->left, key, priority);
if (p->left->priority > p->priority) {
rotateRight(p);
}
} else {
insertUtil(p->right, key, priority);
if (p->right->priority > p->priority) {
rotateLeft(p);
}
}
}
void deleteUtil(Node *&p, int key) {
if (!p) {
return;
}
if (p->key == key) {
if (!p->left && !p->right) {
delete p;
p = NULL;
} else if (!p->left) {
Node *q = p;
p = p->right;
delete q;
} else if (!p->right) {
Node *q = p;
p = p->left;
delete q;
} else {
if (p->left->priority > p->right->priority) {
rotateRight(p);
deleteUtil(p->right, key);
} else {
rotateLeft(p);
deleteUtil(p->left, key);
}
}
} else if (p->key > key
阅读全文