-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRedBlackTree.java
More file actions
321 lines (291 loc) · 11.2 KB
/
RedBlackTree.java
File metadata and controls
321 lines (291 loc) · 11.2 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// --== CS400 File Header Information ==--
// Name: Xiaochen Fan
// Email: xfan72@wisc.edu
// Team: NC
// Front End Developer
// TA: Daniel Finer
// Lecturer: Gary Dahl
// Notes to Grader: <optional extra notes>
import java.util.LinkedList;
// import org.junit.Test;
// import static org.junit.Assert.*;
/**
* Binary Search Tree implementation with a Node inner class for representing the nodes within a
* binary search tree. You can use this class' insert method to build a binary search tree, and its
* toString method to display the level order (breadth first) traversal of values in that tree.
*/
public class RedBlackTree<T extends Comparable<T>> {
/**
* This class represents a node holding a single value within a binary tree the parent, left, and
* right child references are always be maintained.
*/
protected static class Node<T> {
public T data;
public Node<T> parent; // null for root node
public Node<T> leftChild;
public Node<T> rightChild;
public boolean isBlack = false;
public Node(T data) {
this.data = data;
}
/**
* @return true when this node has a parent and is the left child of that parent, otherwise
* return false
*/
public boolean isLeftChild() {
return parent != null && parent.leftChild == this;
}
/**
* @return true when this node has a parent and is the right child of that parent, otherwise
* return false
*/
public boolean isRightChild() {
return parent != null && parent.rightChild == this;
}
/**
* This method performs a level order traversal of the tree rooted at the current node. The
* string representations of each data value within this tree are assembled into a comma
* separated string within brackets (similar to many implementations of java.util.Collection).
*
* @return string containing the values of this tree in level order
*/
@Override
public String toString() { // display subtree in order traversal
String output = "[";
LinkedList<Node<T>> q = new LinkedList<>();
q.add(this);
while (!q.isEmpty()) {
Node<T> next = q.removeFirst();
if (next.leftChild != null)
q.add(next.leftChild);
if (next.rightChild != null)
q.add(next.rightChild);
output += next.data.toString();
if (!q.isEmpty())
output += ", ";
}
return output + "]";
}
public boolean hasSibling() {
if (this.isLeftChild() && this.parent.rightChild != null) {
return true;
} else if (this.isRightChild() && this.parent.leftChild != null) {
return true;
}
return false;
}
public Node getSibling() {
if (this.hasSibling() && this.isLeftChild()) {
return this.parent.rightChild;
} else if (this.hasSibling() && this.isRightChild()) {
return this.parent.leftChild;
}
return null;
}
public boolean isSameSideOfParent() {
if (this.isLeftChild() && this.parent.isLeftChild()) {
return true;
} else if (this.isRightChild() && this.parent.isRightChild()) {
return true;
}
return false;
}
// if this Node is on the opposite of the parent's sibling
public boolean isOppositeSide() {
if (this.isLeftChild() && this.parent.getSibling().isRightChild()) {
return true;
} else if (this.isRightChild() && this.parent.getSibling().isLeftChild()) {
return true;
}
return false;
}
}
protected Node<T> root; // reference to root node of tree, null when empty
/**
* Performs a naive insertion into a binary search tree: adding the input data value to a new node
* in a leaf position within the tree. After this insertion, no attempt is made to restructure or
* balance the tree. This tree will not hold null references, nor duplicate data values.
*
* @param data to be added into this binary search tree
* @throws NullPointerException when the provided data argument is null
* @throws IllegalArgumentException when the tree already contains data
*/
public void insert(T data) throws NullPointerException, IllegalArgumentException {
// null references cannot be stored within this tree
if (data == null)
throw new NullPointerException("This RedBlackTree cannot store null references.");
Node<T> newNode = new Node<>(data);
if (root == null) {
root = newNode;
this.root.isBlack = true;
} // add first node to an empty tree
else
insertHelper(newNode, root); // recursively insert into subtree
}
/**
* Recursive helper method to find the subtree with a null reference in the position that the
* newNode should be inserted, and then extend this tree by the newNode in that position.
*
* @param newNode is the new node that is being added to this tree
* @param subtree is the reference to a node within this tree which the * newNode should be
* inserted as a descenedent beneath
* @throws IllegalArgumentException when the newNode and subtree contain equal data references (as
* defined by Comparable.compareTo())
*/
private void insertHelper(Node<T> newNode, Node<T> subtree) {
int compare = newNode.data.compareTo(subtree.data);
// do not allow duplicate values to be stored within this tree
if (compare == 0)
throw new IllegalArgumentException("This RedBlackTree already contains that value.");
// store newNode within left subtree of subtree
else if (compare < 0) {
if (subtree.leftChild == null) { // left subtree empty, add here
subtree.leftChild = newNode;
newNode.parent = subtree;
enforceRBTreePropertiesAfterInsert(newNode);
// otherwise continue recursive search for location to insert
} else
insertHelper(newNode, subtree.leftChild);
}
// store newNode within the right subtree of subtree
else {
if (subtree.rightChild == null) { // right subtree empty, add here
subtree.rightChild = newNode;
newNode.parent = subtree;
enforceRBTreePropertiesAfterInsert(newNode);
// otherwise continue recursive search for location to insert
} else
insertHelper(newNode, subtree.rightChild);
}
}
/**
* Make sure the whole tree still fits the properties of RBT after every insert
*
*/
private void enforceRBTreePropertiesAfterInsert(Node newNode) {
Node grandP = newNode.parent.parent;
Node P = newNode.parent;
if (grandP != null && P.isBlack != true) {
// Case1
if (P.hasSibling() && P.getSibling().isBlack == false) {
if (P.isRightChild()) {
grandP.leftChild.isBlack = true;
P.isBlack = true;
if (grandP != root) {
grandP.isBlack = false;
}
} else if (P.isLeftChild()) {
grandP.rightChild.isBlack = true;
P.isBlack = true;
if (grandP != root) {
grandP.isBlack = false;
}
}
if (grandP.parent != null && grandP.parent.hasSibling()) {
enforceRBTreePropertiesAfterInsert(grandP);
}
}
// Case2
else if ((!P.hasSibling() && newNode.isSameSideOfParent())
|| (P.hasSibling() && P.getSibling().isBlack == true && newNode.isSameSideOfParent())) {
rotate(P, grandP);
P.isBlack = true;
if (P.leftChild.isBlack == true) {
P.leftChild.isBlack = false;
} else if (P.rightChild.isBlack == true) {
P.rightChild.isBlack = false;
}
}
// Case3
else if ((!P.hasSibling() && !newNode.isSameSideOfParent())
|| (P.hasSibling() && P.getSibling().isBlack == true && !newNode.isSameSideOfParent())) {
boolean isLeft = false;
if (newNode.isLeftChild()) {
isLeft = true;
}
else {
isLeft = false;
}
rotate(newNode, P);
if (isLeft == true) {
enforceRBTreePropertiesAfterInsert(newNode.rightChild);
} else {
enforceRBTreePropertiesAfterInsert(newNode.leftChild);
}
}
}
}
/**
* This method performs a level order traversal of the tree. The string representations of each
* data value within this tree are assembled into a comma separated string within brackets
* (similar to many implementations of java.util.Collection, like java.util.ArrayList, LinkedList,
* etc).
*
* @return string containing the values of this tree in level order
*/
@Override
public String toString() {
return root.toString();
}
/**
* Performs the rotation operation on the provided nodes within this BST. When the provided child
* is a leftChild of the provided parent, this method will perform a right rotation (sometimes
* called a left-right rotation). When the provided child is a rightChild of the provided parent,
* this method will perform a left rotation (sometimes called a right-left rotation). When the
* provided nodes are not related in one of these ways, this method will throw an
* IllegalArgumentException.
*
* @param child is the node being rotated from child to parent position (between these two node
* arguments)
* @param parent is the node being rotated from parent to child position (between these two node
* arguments)
* @throws IllegalArgumentException when the provided child and parent node references are not
* initially (pre-rotation) related that way
*/
private void rotate(Node<T> child, Node<T> parent) throws IllegalArgumentException {
// TODO: Implement this method.
if (child.isLeftChild() && child.parent.equals(parent)) { // left-right rotation
if (!this.root.equals(parent)) {
child.parent = parent.parent;
if (parent.isLeftChild()) {
parent.parent.leftChild = child;
} else {
parent.parent.rightChild = child;
}
} else {
root = child;
}
Node<T> oldRC = child.rightChild;
child.rightChild = parent;
parent.parent = child;
if (oldRC != null) {
oldRC.parent = parent;
parent.leftChild = oldRC;
} else {
parent.leftChild = null;
}
} else if (!child.isLeftChild() && child.parent.equals(parent)) { // right-left rotation
if (!this.root.equals(parent)) {
child.parent = parent.parent;
if (parent.isLeftChild()) {
parent.parent.leftChild = child;
} else {
parent.parent.rightChild = child;
}
} else {
root = child;
}
Node<T> oldLC = child.leftChild;
child.leftChild = parent;
parent.parent = child;
if (oldLC != null) {
oldLC.parent = parent;
parent.rightChild = oldLC;
} else {
parent.rightChild = null;
}
} else {
throw new IllegalArgumentException("Cannot rotate this pair of Nodes.");
}
}
}