Skip to content

Commit b087029

Browse files
authored
Create Treap.cpp
1 parent ba7cf5a commit b087029

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

C++/Treap.cpp

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

0 commit comments

Comments
 (0)