forked from StepJes/Hacktoberfest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTreap_in_Java.java
76 lines (58 loc) · 1.62 KB
/
Treap_in_Java.java
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
74
75
76
import java.util.Random;
class Node {
int key;
int priority;
Node left, right;
Node(int key) {
this.key = key;
this.priority = new Random().nextInt(100); // Assign a random priority
this.left = this.right = null;
}
}
public class Treap {
Node root;
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 == null)
return new Node(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 inorder(Node root) {
if (root != null) {
inorder(root.left);
System.out.println("Key: " + root.key + ", Priority: " + root.priority);
inorder(root.right);
}
}
public static void main(String[] args) {
Treap treap = new Treap();
// Insert keys with random priorities
treap.root = treap.insert(treap.root, 10);
treap.root = treap.insert(treap.root, 20);
treap.root = treap.insert(treap.root, 5);
// Print inorder traversal
treap.inorder(treap.root);
}
}