Implementation of Search, Insert and Delete in Treap
Last Updated :
23 Jul, 2025
We strongly recommend to refer set 1 as a prerequisite of this post.
Treap (A Randomized Binary Search Tree)
In this post, implementations of search, insert and delete are discussed.
Search:
Same as standard BST search. Priority is not considered for search.
C++
// C function to search a given key in a given BST
TreapNode* search(TreapNode* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
Java
// Java function to search a given key in a given BST
public TreapNode search(TreapNode root, int key)
{
// Base Cases: root is null or key is present at root
if (root == null || root.key == key)
return root;
// Key is greater than root's key
if (root.key < key)
return search(root.right, key);
// Key is smaller than root's key
return search(root.left, key);
}
Python3
# Python function to search a given key in a given BST
def search(root, key):
# Base Cases: root is None or key is present at root
if root is None or root.key == key:
return root
# Key is greater than root's key
if root.key < key:
return search(root.right, key)
# Key is smaller than root's key
return search(root.left, key)
# This code is contributed by Amit Mangal.
C#
public static TreapNode search(TreapNode root, int key) {
// Base Cases: root is null or key is present at root
if (root == null || root.key == key) {
return root;
}
// Key is greater than root's key
if (root.key < key) {
return search(root.right, key);
}
// Key is smaller than root's key
return search(root.left, key);
}
JavaScript
function search(root, key) {
// Base Cases: root is null or key is present at root
if (root == null || root.key === key) {
return root;
}
// Key is greater than root's key
if (root.key < key) {
return search(root.right, key);
}
// Key is smaller than root's key
return search(root.left, key);
}
Insert
1) Create new node with key equals to x and value equals to a random value.
2) Perform standard BST insert.
3) A newly inserted node gets a random priority, so Max-Heap property may be violated.. Use rotations to make sure that inserted node's priority follows max heap property.
During insertion, we recursively traverse all ancestors of the inserted node.
a) If new node is inserted in left subtree and root of left subtree has higher priority, perform right rotation.
b) If new node is inserted in right subtree and root of right subtree has higher priority, perform left rotation.
CPP
/* Recursive implementation of insertion in Treap */
TreapNode* insert(TreapNode* root, int key)
{
// If root is NULL, create a new node and return it
if (!root)
return newNode(key);
// If key is smaller than root
if (key <= root->key)
{
// Insert in left subtree
root->left = insert(root->left, key);
// Fix Heap property if it is violated
if (root->left->priority > root->priority)
root = rightRotate(root);
}
else // If key is greater
{
// Insert in right subtree
root->right = insert(root->right, key);
// Fix Heap property if it is violated
if (root->right->priority > root->priority)
root = leftRotate(root);
}
return root;
}
Java
/* Recursive implementation of insertion in Treap */
public TreapNode insert(TreapNode root, int key) {
// If root is null, create a new node and return it
if (root == null) {
return newNode(key);
}
// If key is smaller than root
if (key <= root.key) {
// Insert in left subtree
root.left = insert(root.left, key);
// Fix Heap property if it is violated
if (root.left.priority > root.priority) {
root = rightRotate(root);
}
} else { // If key is greater
// Insert in right subtree
root.right = insert(root.right, key);
// Fix Heap property if it is violated
if (root.right.priority > root.priority) {
root = leftRotate(root);
}
}
return root;
}
Python3
# Recursive implementation of insertion in Treap
def insert(root, key):
# If root is None, create a new node and return it
if root is None:
return newNode(key)
# If key is smaller than root
if key <= root.key:
# Insert in left subtree
root.left = insert(root.left, key)
# Fix Heap property if it is violated
if root.left.priority > root.priority:
root = rightRotate(root)
else: # If key is greater
# Insert in right subtree
root.right = insert(root.right, key)
# Fix Heap property if it is violated
if root.right.priority > root.priority:
root = leftRotate(root)
return root
# This code is contributed by Amit Mangal.
C#
public TreapNode Insert(TreapNode root, int key)
{
// If root is null, create a new node and return it
if (root == null)
return NewNode(key);
// If key is smaller than root
if (key <= root.Key)
{
// Insert in left subtree
root.Left = Insert(root.Left, key);
// Fix Heap property if it is violated
if (root.Left.Priority > root.Priority)
root = RightRotate(root);
}
else // If key is greater
{
// Insert in right subtree
root.Right = Insert(root.Right, key);
// Fix Heap property if it is violated
if (root.Right.Priority > root.Priority)
root = LeftRotate(root);
}
return root;
}
JavaScript
function insert(root, key) {
// If root is null, create a new node and return it
if (root == null) {
return newNode(key);
}
// If key is smaller than root
if (key <= root.key) {
// Insert in left subtree
root.left = insert(root.left, key);
// Fix Heap property if it is violated
if (root.left.priority > root.priority) {
root = rightRotate(root);
}
} else { // If key is greater
// Insert in right subtree
root.right = insert(root.right, key);
// Fix Heap property if it is violated
if (root.right.priority > root.priority) {
root = leftRotate(root);
}
}
return root;
}
Delete:
The delete implementation here is slightly different from the steps discussed in previous post.
1) If node is a leaf, delete it.
2) If node has one child NULL and other as non-NULL, replace node with the non-empty child.
3) If node has both children as non-NULL, find max of left and right children.
....a) If priority of right child is greater, perform left rotation at node
....b) If priority of left child is greater, perform right rotation at node.
The idea of step 3 is to move the node to down so that we end up with either case 1 or case 2.
CPP
/* Recursive implementation of Delete() */
TreapNode* deleteNode(TreapNode* root, int key)
{
// Base case
if (root == NULL) return root;
// IF KEYS IS NOT AT ROOT
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
// IF KEY IS AT ROOT
// If left is NULL
else if (root->left == NULL)
{
TreapNode *temp = root->right;
delete(root);
root = temp; // Make right child as root
}
// If Right is NULL
else if (root->right == NULL)
{
TreapNode *temp = root->left;
delete(root);
root = temp; // Make left child as root
}
// If key is at root and both left and right are not NULL
else if (root->left->priority < root->right->priority)
{
root = leftRotate(root);
root->left = deleteNode(root->left, key);
}
else
{
root = rightRotate(root);
root->right = deleteNode(root->right, key);
}
return root;
}
Java
/* Recursive implementation of delete() */
public TreapNode deleteNode(TreapNode root, int key)
{
// Base case
if (root == null) {
return root;
}
// IF KEY IS NOT AT ROOT
if (key < root.key) {
root.left = deleteNode(root.left, key);
}
else if (key > root.key) {
root.right = deleteNode(root.right, key);
}
// IF KEY IS AT ROOT
// If left is null
else if (root.left == null) {
TreapNode temp = root.right;
root = null;
root = temp; // Make right child as root
}
// If right is null
else if (root.right == null) {
TreapNode temp = root.left;
root = null;
root = temp; // Make left child as root
}
// If key is at root and both left and right are not
// null
else if (root.left.priority < root.right.priority) {
root = leftRotate(root);
root.left = deleteNode(root.left, key);
}
else {
root = rightRotate(root);
root.right = deleteNode(root.right, key);
}
return root;
}
Python3
def deleteNode(root, key):
# Base case
if not root:
return root
# IF KEYS IS NOT AT ROOT
if key < root.key:
root.left = deleteNode(root.left, key)
elif key > root.key:
root.right = deleteNode(root.right, key)
# IF KEY IS AT ROOT
# If left is NULL
elif not root.left:
temp = root.right
del root
root = temp # Make right child as root
# If Right is NULL
elif not root.right:
temp = root.left
del root
root = temp # Make left child as root
# If key is at root and both left and right are not NULL
elif root.left.priority < root.right.priority:
root = rightRotate(root)
root.right = deleteNode(root.right, key)
else:
root = leftRotate(root)
root.left = deleteNode(root.left, key)
return root
# This code is contributed by Amit Mangal.
C#
public TreapNode DeleteNode(TreapNode root, int key)
{
// Base case
if (root == null) return root;
// If key is not at root
if (key < root.Key)
root.Left = DeleteNode(root.Left, key);
else if (key > root.Key)
root.Right = DeleteNode(root.Right, key);
// If key is at root
// If left is null
else if (root.Left == null)
{
TreapNode temp = root.Right;
root = temp; // Make right child as root
}
// If right is null
else if (root.Right == null)
{
TreapNode temp = root.Left;
root = temp; // Make left child as root
}
// If key is at root and both left and right are not null
else if (root.Left.Priority < root.Right.Priority)
{
root = LeftRotate(root);
root.Left = DeleteNode(root.Left, key);
}
else
{
root = RightRotate(root);
root.Right = DeleteNode(root.Right, key);
}
return root;
}
JavaScript
function deleteNode(root, key) {
// Base case
if (root == null) return root;
// IF KEYS IS NOT AT ROOT
if (key < root.key) {
root.left = deleteNode(root.left, key);
} else if (key > root.key) {
root.right = deleteNode(root.right, key);
}
// IF KEY IS AT ROOT
else if (root.left == null) {
let temp = root.right;
delete root;
root = temp; // Make right child as root
} else if (root.right == null) {
let temp = root.left;
delete root;
root = temp; // Make left child as root
} else if (root.left.priority < root.right.priority) {
root = leftRotate(root);
root.left = deleteNode(root.left, key);
} else {
root = rightRotate(root);
root.right = deleteNode(root.right, key);
}
return root;
}
A Complete Program to Demonstrate All Operations
CPP
// C++ program to demonstrate search, insert and delete in Treap
#include <bits/stdc++.h>
using namespace std;
// A Treap Node
struct TreapNode
{
int key, priority;
TreapNode *left, *right;
};
/* T1, T2 and T3 are subtrees of the tree rooted with y
(on left side) or x (on right side)
y x
/ \ Right Rotation / \
x T3 – – – – – – – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3 */
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
TreapNode *rightRotate(TreapNode *y)
{
TreapNode *x = y->left, *T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
TreapNode *leftRotate(TreapNode *x)
{
TreapNode *y = x->right, *T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Return new root
return y;
}
/* Utility function to add a new key */
TreapNode* newNode(int key)
{
TreapNode* temp = new TreapNode;
temp->key = key;
temp->priority = rand()%100;
temp->left = temp->right = NULL;
return temp;
}
// C function to search a given key in a given BST
TreapNode* search(TreapNode* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
/* Recursive implementation of insertion in Treap */
TreapNode* insert(TreapNode* root, int key)
{
// If root is NULL, create a new node and return it
if (!root)
return newNode(key);
// If key is smaller than root
if (key <= root->key)
{
// Insert in left subtree
root->left = insert(root->left, key);
// Fix Heap property if it is violated
if (root->left->priority > root->priority)
root = rightRotate(root);
}
else // If key is greater
{
// Insert in right subtree
root->right = insert(root->right, key);
// Fix Heap property if it is violated
if (root->right->priority > root->priority)
root = leftRotate(root);
}
return root;
}
/* Recursive implementation of Delete() */
TreapNode* deleteNode(TreapNode* root, int key)
{
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
// IF KEY IS AT ROOT
// If left is NULL
else if (root->left == NULL)
{
TreapNode *temp = root->right;
delete(root);
root = temp; // Make right child as root
}
// If Right is NULL
else if (root->right == NULL)
{
TreapNode *temp = root->left;
delete(root);
root = temp; // Make left child as root
}
// If key is at root and both left and right are not NULL
else if (root->left->priority < root->right->priority)
{
root = leftRotate(root);
root->left = deleteNode(root->left, key);
}
else
{
root = rightRotate(root);
root->right = deleteNode(root->right, key);
}
return root;
}
// A utility function to print tree
void inorder(TreapNode* root)
{
if (root)
{
inorder(root->left);
cout << "key: "<< root->key << " | priority: %d "
<< root->priority;
if (root->left)
cout << " | left child: " << root->left->key;
if (root->right)
cout << " | right child: " << root->right->key;
cout << endl;
inorder(root->right);
}
}
// Driver Program to test above functions
int main()
{
srand(time(NULL));
struct TreapNode *root = NULL;
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);
cout << "Inorder traversal of the given tree \n";
inorder(root);
cout << "\nDelete 20\n";
root = deleteNode(root, 20);
cout << "Inorder traversal of the modified tree \n";
inorder(root);
cout << "\nDelete 30\n";
root = deleteNode(root, 30);
cout << "Inorder traversal of the modified tree \n";
inorder(root);
cout << "\nDelete 50\n";
root = deleteNode(root, 50);
cout << "Inorder traversal of the modified tree \n";
inorder(root);
TreapNode *res = search(root, 50);
(res == NULL)? cout << "\n50 Not Found ":
cout << "\n50 found";
return 0;
}
Java
/*package whatever //do not write package name here */
import java.util.*;
// A Treap Node
class TreapNode
{
int key,priority;
TreapNode left,right;
}
/* T1, T2 and T3 are subtrees of the tree rooted with y
(on left side) or x (on right side)
y x
/ \ Right Rotation / \
x T3 – – – – – – – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3 */
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
class Main
{
public static TreapNode rightRotate(TreapNode y) {
TreapNode x = y.left;
TreapNode T2 = x.right;
// Perform rotation
x.right = y;
y.left = T2;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
public static TreapNode leftRotate(TreapNode x) {
TreapNode y = x.right;
TreapNode T2 = y.left;
// Perform rotation
y.left = x;
x.right = T2;
// Return new root
return y;
}
/* Utility function to add a new key */
public static TreapNode newNode(int key) {
TreapNode temp = new TreapNode();
temp.key = key;
temp.priority = (int)(Math.random() * 100);
temp.left = temp.right = null;
return temp;
}
/* Recursive implementation of insertion in Treap */
public static TreapNode insert(TreapNode root, int key) {
// If root is null, create a new node and return it
if (root == null) {
return newNode(key);
}
// If key is smaller than root
if (key <= root.key) {
// Insert in left subtree
root.left = insert(root.left, key);
// Fix Heap property if it is violated
if (root.left.priority > root.priority) {
root = rightRotate(root);
}
} else { // If key is greater
// Insert in right subtree
root.right = insert(root.right, key);
// Fix Heap property if it is violated
if (root.right.priority > root.priority) {
root = leftRotate(root);
}
}
return root;
}
/* Recursive implementation of Delete() */
public static TreapNode deleteNode(TreapNode root, int key) {
if (root == null)
return root;
if (key < root.key)
root.left = deleteNode(root.left, key);
else if (key > root.key)
root.right = deleteNode(root.right, key);
// IF KEY IS AT ROOT
// If left is NULL
else if (root.left == null)
{
TreapNode temp = root.right;
root = temp; // Make right child as root
}
// If Right is NULL
else if (root.right == null)
{
TreapNode temp = root.left;
root = temp; // Make left child as root
}
// If key is at root and both left and right are not NULL
else if (root.left.priority < root.right.priority)
{
root = leftRotate(root);
root.left = deleteNode(root.left, key);
}
else
{
root = rightRotate(root);
root.right = deleteNode(root.right, key);
}
return root;
}
// Java function to search a given key in a given BST
public static TreapNode search(TreapNode root, int key)
{
// Base Cases: root is null or key is present at root
if (root == null || root.key == key)
return root;
// Key is greater than root's key
if (root.key < key)
return search(root.right, key);
// Key is smaller than root's key
return search(root.left, key);
}
static void inorder(TreapNode root)
{
if (root != null)
{
inorder(root.left);
System.out.print("key: " + root.key + " | priority: " + root.priority);
if (root.left != null)
System.out.print(" | left child: " + root.left.key);
if (root.right != null)
System.out.print(" | right child: " + root.right.key);
System.out.println();
inorder(root.right);
}
}
// Driver Program to test above functions
public static void main(String[] args)
{
Random rand = new Random();
TreapNode root = null;
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);
System.out.println("Inorder traversal of the given tree:");
inorder(root);
System.out.println("\nDelete 20");
root = deleteNode(root, 20);
System.out.println("Inorder traversal of the modified tree:");
inorder(root);
System.out.println("\nDelete 30");
root = deleteNode(root, 30);
System.out.println("Inorder traversal of the modified tree:");
inorder(root);
System.out.println("\nDelete 50");
root = deleteNode(root, 50);
System.out.println("Inorder traversal of the modified tree:");
inorder(root);
TreapNode res = search(root, 50);
System.out.println(res == null ? "\n50 Not Found" : "\n50 found");
}
}
Python3
import random
# A Treap Node
class TreapNode:
def __init__(self, key):
self.key = key
self.priority = random.randint(0, 99)
self.left = None
self.right = None
# T1, T2 and T3 are subtrees of the tree rooted with y
# (on left side) or x (on right side)
# y x
# / \ Right Rotation / \
# x T3 – – – – – – – > T1 y
# / \ < - - - - - - - / \
# T1 T2 Left Rotation T2 T3 */
# A utility function to right rotate subtree rooted with y
# See the diagram given above.
def rightRotate(y):
x = y.left
T2 = x.right
# Perform rotation
x.right = y
y.left = T2
# Return new root
return x
def leftRotate(x):
y = x.right
T2 = y.left
# Perform rotation
y.left = x
x.right = T2
# Return new root
return y
def insert(root, key):
# If root is None, create a new node and return it
if not root:
return TreapNode(key)
# If key is smaller than root
if key <= root.key:
# Insert in left subtree
root.left = insert(root.left, key)
# Fix Heap property if it is violated
if root.left.priority > root.priority:
root = rightRotate(root)
else:
# Insert in right subtree
root.right = insert(root.right, key)
# Fix Heap property if it is violated
if root.right.priority > root.priority:
root = leftRotate(root)
return root
def deleteNode(root, key):
if not root:
return root
if key < root.key:
root.left = deleteNode(root.left, key)
elif key > root.key:
root.right = deleteNode(root.right, key)
else:
# IF KEY IS AT ROOT
# If left is None
if not root.left:
temp = root.right
root = None
return temp
# If right is None
elif not root.right:
temp = root.left
root = None
return temp
# If key is at root and both left and right are not None
elif root.left.priority < root.right.priority:
root = leftRotate(root)
root.left = deleteNode(root.left, key)
else:
root = rightRotate(root)
root.right = deleteNode(root.right, key)
return root
# A utility function to search a given key in a given BST
def search(root, key):
# Base Cases: root is None or key is present at root
if not root or root.key == key:
return root
# Key is greater than root's key
if root.key < key:
return search(root.right, key)
# Key is smaller than root's key
return search(root.left, key)
# A utility function to print tree
def inorder(root):
if root:
inorder(root.left)
print("key:", root.key, "| priority:", root.priority, end="")
if root.left:
print(" | left child:", root.left.key, end="")
if root.right:
print(" | right child:", root.right.key, end="")
print()
inorder(root.right)
# Driver Program to test above functions
if __name__ == '__main__':
random.seed(0)
root = None
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)
print("Inorder traversal of the given tree")
inorder(root)
print("\nDelete 20")
root = deleteNode(root, 20)
print("Inorder traversal of the modified tree")
inorder(root)
print("\nDelete 30")
root = deleteNode(root, 30)
print("Inorder traversal of the modified tree")
inorder(root)
print("\nDelete 50")
root = deleteNode(root, 50)
print("Inorder traversal of the modified tree")
inorder(root)
res = search(root, 50)
if res is None:
print("50 Not Found")
else:
print("50 found")
# This code is contributed by Amit Mangal.
C#
using System;
// A Treap Node
class TreapNode
{
public int key, priority;
public TreapNode left, right;
}
/* T1, T2 and T3 are subtrees of the tree rooted with y
(on left side) or x (on right side)
y x
/ \ Right Rotation / \
x T3 – – – – – – – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3 */
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
class Program
{
static Random rand = new Random();
// A utility function to right rotate subtree
static TreapNode rightRotate(TreapNode y)
{
TreapNode x = y.left;
TreapNode T2 = x.right;
// Perform rotation
x.right = y;
y.left = T2;
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
static TreapNode leftRotate(TreapNode x)
{
TreapNode y = x.right;
TreapNode T2 = y.left;
// Perform rotation
y.left = x;
x.right = T2;
return y;
}
/* Utility function to add a new key */
static TreapNode newNode(int key)
{
TreapNode temp = new TreapNode();
temp.key = key;
temp.priority = rand.Next(100);
temp.left = temp.right = null;
return temp;
}
/* Recursive implementation of insertion in Treap */
static TreapNode insert(TreapNode root, int key)
{
// If root is null, create a new node and return it
if (root == null)
{
return newNode(key);
}
// If key is smaller than root
if (key <= root.key)
{
root.left = insert(root.left, key);
// Fix Heap property if it is violated
if (root.left.priority > root.priority)
{
root = rightRotate(root);
}
}
else
{// If key is greater
// Insert in right subtree
root.right = insert(root.right, key);
// Fix Heap property if it is violated
if (root.right.priority > root.priority)
{
root = leftRotate(root);
}
}
return root;
}
/* Recursive implementation of Delete() */
static TreapNode deleteNode(TreapNode root, int key)
{
if (root == null)
{
return root;
}
if (key < root.key)
{
root.left = deleteNode(root.left, key);
}
else if (key > root.key)
{
root.right = deleteNode(root.right, key);
}
// IF KEY IS AT ROOT
// If left is NULL
else if (root.left == null)
{
TreapNode temp = root.right;
root = temp; // Make right child as root
}
// If right is NULL
else if (root.right == null)
{
TreapNode temp = root.left;
root = temp; // Make left child as root
}
// If key is at root and both left and right are not NULL
else if (root.left.priority < root.right.priority)
{
root = leftRotate(root);
root.left = deleteNode(root.left, key);
}
else
{
root = rightRotate(root);
root.right = deleteNode(root.right, key);
}
return root;
}
// Function to search a given key in a given BST
static TreapNode search(TreapNode root, int key)
{
// Base Cases: root is null or key is present at root
if (root == null || root.key == key)
{
return root;
}
// Key is greater than root's key
if (root.key < key)
{
return search(root.right, key);
}
// Key is smaller than root's key
return search(root.left, key);
}
// A utility function to print tree
static void inorder(TreapNode root)
{
if (root != null)
{
inorder(root.left);
Console.Write("key: " + root.key + " | priority: " + root.priority);
if (root.left != null)
{
Console.Write(" | left child: " + root.left.key);
}
if (root.right != null)
{
Console.Write(" | right child: " + root.right.key);
}
Console.WriteLine();
inorder(root.right);
}
}
// Driver Code
static void Main(string[] args)
{
TreapNode root = null;
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);
Console.WriteLine("Inorder traversal of the given tree:");
inorder(root);
Console.WriteLine("\nDelete 20");
root = deleteNode(root, 20);
Console.WriteLine("Inorder traversal of the modified tree:");
inorder(root);
Console.WriteLine("\nDelete 30");
root = deleteNode(root, 30);
Console.WriteLine("Inorder traversal of the modified tree:");
inorder(root);
Console.WriteLine("\nDelete 50");
root = deleteNode(root, 50);
Console.WriteLine("Inorder traversal of the modified tree:");
inorder(root);
TreapNode res = search(root, 50);
Console.WriteLine(res == null ? "\n50 Not Found" : "\n50 found");
}
};
JavaScript
// A Treap Node
class TreapNode {
constructor(key) {
this.key = key;
this.priority = Math.floor(Math.random() * 100);
this.left = null;
this.right = null;
}
}
/* T1, T2, and T3 are subtrees of the tree rooted with y
(on the left side) or x (on the right side)
y x
/ \ Right Rotation / \
x T3 – – – – – – – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3 */
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
function rightRotate(y) {
let x = y.left;
let T2 = x.right;
// Perform rotation
x.right = y;
y.left = T2;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
function leftRotate(x) {
let y = x.right;
let T2 = y.left;
// Perform rotation
y.left = x;
x.right = T2;
// Return new root
return y;
}
/* Utility function to add a new key */
function newNode(key) {
let temp = new TreapNode(key);
return temp;
}
// JavaScript implementation of search in a given Treap
function search(root, key) {
// Base Cases: root is null or key is present at root
if (root === null || root.key === key)
return root;
// Key is greater than root's key
if (root.key < key)
return search(root.right, key);
// Key is smaller than root's key
return search(root.left, key);
}
/* Recursive implementation of insertion in Treap */
function insert(root, key) {
// If root is null, create a new node and return it
if (!root)
return newNode(key);
// If key is smaller than root
if (key <= root.key) {
// Insert in the left subtree
root.left = insert(root.left, key);
// Fix Heap property if it is violated
if (root.left.priority > root.priority)
root = rightRotate(root);
} else { // If key is greater
// Insert in the right subtree
root.right = insert(root.right, key);
// Fix Heap property if it is violated
if (root.right.priority > root.priority)
root = leftRotate(root);
}
return root;
}
/* Recursive implementation of Delete() */
function deleteNode(root, key) {
if (root === null)
return root;
if (key < root.key)
root.left = deleteNode(root.left, key);
else if (key > root.key)
root.right = deleteNode(root.right, key);
// IF KEY IS AT ROOT
// If left is NULL
else if (root.left === null) {
let temp = root.right;
root = temp; // Make the right child the root
}
// If Right is NULL
else if (root.right === null) {
let temp = root.left;
root = temp; // Make the left child the root
}
// If the key is at the root, and both left and right are not NULL
else if (root.left.priority < root.right.priority) {
root = leftRotate(root);
root.left = deleteNode(root.left, key);
} else {
root = rightRotate(root);
root.right = deleteNode(root.right, key);
}
return root;
}
// A utility function to print tree
function inorder(root) {
if (root) {
inorder(root.left);
console.log(`key: ${root.key} | priority: ${root.priority}`);
if (root.left)
console.log(` | left child: ${root.left.key}`);
if (root.right)
console.log(` | right child: ${root.right.key}`);
console.log();
inorder(root.right);
}
}
// Driver Program to test above functions
function main() {
let root = null;
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);
console.log("Inorder traversal of the given tree");
inorder(root);
console.log("\nDelete 20");
root = deleteNode(root, 20);
console.log("Inorder traversal of the modified tree");
inorder(root);
console.log("\nDelete 30");
root = deleteNode(root, 30);
console.log("Inorder traversal of the modified tree");
inorder(root);
console.log("\nDelete 50");
root = deleteNode(root, 50);
console.log("Inorder traversal of the modified tree");
inorder(root);
let res = search(root, 50);
console.log(res === null ? "\n50 Not Found" : "\n50 found");
}
main();
// Contributed by siddhesh
Output...eft child: 20 | right child: 40
key: 40 | priority: %d 87 | right child: 60
key: 50 | priority: %d 46
key: 60 | priority: %d 62 | left child: 50 | right child: 80
key: 70 | priority: %d 10
key: 80 | priority: %d 57 | left child: 70
Delete 20
Inorder traversal of the modified tree
key: 30 | priority: %d 92 | right child: 40
key: 40 | priority: %d 87 | right child: 60
key: 50 | priority: %d 46
key: 60 | priority: %d 62 | left child: 50 | right child: 80
key: 70 | priority: %d 10
key: 80 | priority: %d 57 | left child: 70
Delete 30
Inorder traversal of the modified tree
key: 40 | priority: %d 87 | right child: 60
key: 50 | priority: %d 46
key: 60 | priority: %d 62 | left child: 50 | right child: 80
key: 70 | priority: %d 10
key: 80 | priority: %d 57 | left child: 70
Delete 50
Inorder traversal of the modified tree
key: 40 | priority: %d 87 | right child: 60
key: 60 | priority: %d 62 | right child: 80
key: 70 | priority: %d 10
key: 80 | priority: %d 57 | left child: 70
50 Not Found
Explanation of the above output:
Every node is written as key(priority)
The above code constructs below tree
20(92)
\
50(73)
/ \
30(48) 60(55)
\ \
40(21) 70(50)
\
80(44)
After deleteNode(20)
50(73)
/ \
30(48) 60(55)
\ \
40(21) 70(50)
\
80(44)
After deleteNode(30)
50(73)
/ \
40(21) 60(55)
\
70(50)
\
80(44)
After deleteNode(50)
60(55)
/ \
40(21) 70(50)
\
80(44)
Thanks to Jai Goyal for providing an initial implementation.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem