Skip to content

Commit 9841ed0

Browse files
authored
Create Treap.c
1 parent 977dd87 commit 9841ed0

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

Coding/Treap.c

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <time.h>
4+
5+
struct Node {
6+
int key;
7+
int priority;
8+
struct Node* left;
9+
struct Node* right;
10+
};
11+
12+
struct Node* createNode(int key) {
13+
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
14+
if (!newNode) {
15+
perror("Memory allocation failed");
16+
exit(EXIT_FAILURE);
17+
}
18+
newNode->key = key;
19+
newNode->priority = rand();
20+
newNode->left = newNode->right = NULL;
21+
return newNode;
22+
}
23+
24+
struct Node* rotateRight(struct Node* y) {
25+
struct Node* x = y->left;
26+
struct Node* T2 = x->right;
27+
28+
x->right = y;
29+
y->left = T2;
30+
31+
return x;
32+
}
33+
34+
struct Node* rotateLeft(struct Node* x) {
35+
struct Node* y = x->right;
36+
struct Node* T2 = y->left;
37+
38+
y->left = x;
39+
x->right = T2;
40+
41+
return y;
42+
}
43+
44+
struct Node* insert(struct Node* root, int key) {
45+
if (!root) return createNode(key);
46+
47+
if (key <= root->key) {
48+
root->left = insert(root->left, key);
49+
if (root->left->priority > root->priority)
50+
root = rotateRight(root);
51+
} else {
52+
root->right = insert(root->right, key);
53+
if (root->right->priority > root->priority)
54+
root = rotateLeft(root);
55+
}
56+
57+
return root;
58+
}
59+
60+
void inorderTraversal(struct Node* root) {
61+
if (root) {
62+
inorderTraversal(root->left);
63+
printf("(%d, %d) ", root->key, root->priority);
64+
inorderTraversal(root->right);
65+
}
66+
}
67+
68+
int main() {
69+
struct Node* root = NULL;
70+
srand(time(NULL));
71+
72+
root = insert(root, 50);
73+
root = insert(root, 30);
74+
root = insert(root, 20);
75+
root = insert(root, 40);
76+
root = insert(root, 70);
77+
root = insert(root, 60);
78+
root = insert(root, 80);
79+
80+
printf("Inorder traversal of the treap:\n");
81+
inorderTraversal(root);
82+
printf("\n");
83+
84+
return 0;
85+
}

0 commit comments

Comments
 (0)