-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreap.java
More file actions
83 lines (71 loc) · 1.45 KB
/
Copy pathTreap.java
File metadata and controls
83 lines (71 loc) · 1.45 KB
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
77
78
79
80
81
82
83
// YOU SHOULD NOT MODIFY THIS FILE AT ALL.
// (This version will be used by the autograder; not yours!)
import java.util.Comparator;
import java.util.Random;
public class Treap<T> extends
BinarySearchTree<Treap.Node<T>, T> implements SSet<T> {
/**
* A random number source
*/
Random rand;
protected static class Node<T> extends BinarySearchTree.BSTNode<Node<T>,T> {
int p;
}
public Treap(Comparator<T> c) {
super(new Node<T>(), c);
rand = new Random();
}
public Treap() {
this(new DefaultComparator<T>());
}
public boolean add(T x) {
Node<T> u = newNode();
u.x = x;
u.p = rand.nextInt();
if (super.add(u)) {
bubbleUp(u);
return true;
}
return false;
}
protected void bubbleUp(Node<T> u) {
while (u.parent != nil && u.parent.p > u.p) {
if (u.parent.right == u) {
rotateLeft(u.parent);
} else {
rotateRight(u.parent);
}
}
if (u.parent == nil) {
r = u;
}
}
public boolean remove(T x) {
Node<T> u = findLast(x);
if (u != nil && c.compare(u.x, x) == 0) {
trickleDown(u);
splice(u);
return true;
}
return false;
}
/**
* Do rotations to make u a leaf
*/
protected void trickleDown(Node<T> u) {
while (u.left != nil || u.right != nil) {
if (u.left == nil) {
rotateLeft(u);
} else if (u.right == nil) {
rotateRight(u);
} else if (u.left.p < u.right.p) {
rotateRight(u);
} else {
rotateLeft(u);
}
if (r == u) {
r = u.parent;
}
}
}
}