Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Treap.cpp #126

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions Pull Here/CodeChef/Treap.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#include <iostream>
#include <cstdlib>
#include <ctime>

struct Node {
int key;
int priority;
Node* left;
Node* right;
};

Node* createNode(int key) {
Node* newNode = new Node;
newNode->key = key;
newNode->priority = rand();
newNode->left = newNode->right = nullptr;
return newNode;
}

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) {
if (!root) return createNode(key);

if (key <= root->key) {
root->left = insert(root->left, key);
if (root->left->priority > root->priority)
root = rotateRight(root);
} else {
root->right = insert(root->right, key);
if (root->right->priority > root->priority)
root = rotateLeft(root);
}

return root;
}

void inorderTraversal(Node* root) {
if (root) {
inorderTraversal(root->left);
std::cout << "(" << root->key << ", " << root->priority << ") ";
inorderTraversal(root->right);
}
}

int main() {
Node* root = nullptr;
srand(time(nullptr));

root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

std::cout << "Inorder traversal of the treap:" << std::endl;
inorderTraversal(root);
std::cout << std::endl;

return 0;
}