forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreap.cpp
73 lines (54 loc) · 1.35 KB
/
Treap.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <cstdlib>
using namespace std;
struct Node {
int key;
int priority;
Node* left;
Node* right;
Node(int k, int p) : key(k), priority(p), left(NULL), right(NULL) {}
};
Node* rotateRight(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
return x;
}
Node* rotateLeft(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
return y;
}
Node* insert(Node* root, int key, int priority) {
if (root == NULL) return new Node(key, priority);
if (key <= root->key) {
root->left = insert(root->left, key, priority);
if (root->left->priority > root->priority)
root = rotateRight(root);
} else {
root->right = insert(root->right, key, priority);
if (root->right->priority > root->priority)
root = rotateLeft(root);
}
return root;
}
void inorder(Node* root) {
if (root) {
inorder(root->left);
cout << "Key: " << root->key << ", Priority: " << root->priority << endl;
inorder(root->right);
}
}
int main() {
Node* root = NULL;
// Insert keys with random priorities
root = insert(root, 10, 5);
root = insert(root, 20, 10);
root = insert(root, 5, 15);
// Print inorder traversal
inorder(root);
return 0;
}