-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBloatNode.java
More file actions
121 lines (105 loc) · 2.54 KB
/
BloatNode.java
File metadata and controls
121 lines (105 loc) · 2.54 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
public class BloatNode<E extends Comparable<E>> {
int depth = 0;
int count = 0;
E data;
BloatNode<E> left;
BloatNode<E> right;
public static void main(String[] a) {
BloatNode<Integer> tree = new BloatNode<>();
for (int i = 0; i < 20; i++) {
System.out.println(tree);
tree.insert(i);
}
for (int i = 0; i < 10; i++) {
System.out.println(tree);
tree.remove(2*i);
}
for (int i = 0; i < 20; i++) {
System.out.println(tree.query(i));
}
System.out.println(tree);
}
public String toString() {
return depth == 0
? "."
: depth == 1
? data.toString()
: "(" + left.toString() + " " + data.toString() + " " + right.toString() + ")";
}
void insert(E toInsert) {
if (depth == 0) {
data = toInsert;
depth = 1;
count = 1;
left = new BloatNode();
right = new BloatNode();
} else if (toInsert.compareTo(data) == 0) {
count += 1;
} else {
(toInsert.compareTo(data) < 0 ? left : right).insert(toInsert);
balance();
}
}
void balance() {
if (left.depth > right.depth + 1) {
if (left.left.depth < left.right.depth) {
left.rotateLeft();
}
rotateRight();
} else if (left.depth + 1 < right.depth) {
if (right.left.depth > right.right.depth) {
right.rotateRight();
}
rotateLeft();
}
updateDepth();
}
void rotateRight() {
BloatNode<E> a = left.left;
BloatNode<E> b = left.right;
BloatNode<E> c = right;
swap(left);
right = left;
left = a;
right.left = b;
right.right = c;
right.updateDepth();
}
void rotateLeft() {
BloatNode<E> a = left;
BloatNode<E> b = right.left;
BloatNode<E> c = right.right;
swap(right);
left = right;
left.left = a;
left.right = b;
right = c;
left.updateDepth();
}
void swap(BloatNode<E> other) {
E otherData = other.data;
other.data = data;
data = otherData;
int otherCount = other.count;
other.count = count;
count = otherCount;
}
void updateDepth() {
depth = 1 + Math.max(left.depth, right.depth);
}
void remove(E toRemove) {
if (stopSearch(toRemove)) {
count = Math.max(0, count - 1);
} else {
(toRemove.compareTo(data) < 0 ? left : right).remove(toRemove);
}
}
boolean stopSearch(E toFind) {
return depth == 0 || toFind.compareTo(data) == 0;
}
int query(E toFind) {
return (stopSearch(toFind))
? count
: (toFind.compareTo(data) < 0 ? left : right).query(toFind);
}
}