How to Implement a Red Black Tree

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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import java.util.ArrayList;


public class RedBlackTree<K extends Comparable<K>, V> {

private static final boolean RED = true;
private static final boolean BLACK = false;

private Node root;

private int size;

public static void main(String[] args) {
ArrayList<Integer> words = new ArrayList<>();

for (int i = 0; i < 10000; i++) {
words.add(i);
}

RedBlackTree<Integer, Integer> tree = new RedBlackTree<>();

for (Integer word : words) {
if (!tree.contains(word)) {
tree.insert(word, 0);
}

tree.set(word, tree.search(word).value + 1);
}

System.out.println("Height: " + tree.getHeight(tree.root));

System.out.println(tree.getMin().key + ": " + tree.getMin().value);

tree.remove(tree.getMin().key);

System.out.println(tree.getMin().key + ": " + tree.getMin().value);

System.out.println("Is valid BST? " + tree.isBST());
}

/**
* Check out if given node is of red color. Empty node should be considered as BLACK.
*
* @param node
* @return
*/
private boolean isRed(Node node) {
// empty node is black
if (node == null) {
return BLACK;
}

return node.color;
}

/**
* Rotate when right red, left black
*
* @param node
* @return
*/
private Node leftRotate(Node node) {
// node nodex
// / \ left rotate / \
// L nodex ------------> node XR
// / \ / \
// XL XR L XL

// right child nodex is red, becomes the new root

Node nodex = node.right;

// node.right -> XL
node.right = nodex.left;

// nodex.left -> node
nodex.left = node;

// if node.color is red, nodex must be black?
// nodex.color should be set to node.color because nodex replace node's position, also
// need to inherit its color to make the structure stable.
nodex.color = node.color;

// node becomes red
node.color = RED;

// after rotation, nodex.left = node = red, nodex.left.left = node.left = red

return nodex;
}

/**
* Rotate when left red, left.left red
*
* @param node
* @return
*/
private Node rightRotate(Node node) {
// node nodex
// / \ right rotate / \
// nodex R ---------> XL node
// / \ / \
// XL XR XR R

Node nodex = node.left;

// node.left -> XR
node.left = nodex.right;

// nodex.right -> node
nodex.right = node;

// if node.color is red, nodex must be black?
nodex.color = node.color;

node.color = RED;

// after rotation, nodex.left = red, nodex.right = red

return nodex;
}

/**
* Insert content to BST
*
* @param key
* @param value
*/
public void insert(K key, V value) {
root = insert(root, key, value);

// root should be black
root.color = BLACK;
}

/**
* Insert content under a specific node and adjust the balance of the tree afterwards, usually called by
* <code>{@link #insert(K, V)}</code>.
*
* @param node
* @param key
* @param value
* @return
*/
private Node insert(Node node, K key, V value) {
if (node == null) {
size++;

// The default color of the newly create node is RED
return new Node(key, value);
}

// insert to left branch
if (key.compareTo(node.key) < 0) {
node.left = insert(node.left, key, value);
}
// insert to right branch
else if (key.compareTo(node.key) > 0) {
node.right = insert(node.right, key, value);
}
// update the node with given value instead of creating a new one
else {
node.value = value;
}

// Then adjust node colors to make the tree balanced after insertion.

return keepBalanced(node);
}

/**
* Adjust the tree to make it balanced.
*
* @param node
* @return
*/
private Node keepBalanced(Node node) {
// 3 situations

// Node color being red represents it's not the root of the tree, but neither
// the empty node.

// 1. right red, left black

// If current is the parent of new add node, it should be appended on the right and
// left branch is null.

// If the newly inserted node is under node.right, may cause left rotate. Assume current
// node is a leaf node, after insert the new node, node.right=new_node, node.left=null.

// If the inserted nodes are in ascending order, it will continuously appending after the
// right most node which will trigger continuously left rotating.
if (isRed(node.right) && !isRed(node.left)) {
node = leftRotate(node);

// after rotate, node.left=red, node.left.left=black
}

// 2. left red, left.left red, children of red node should be black

// this condition will never gets hit when above condition established and the tree get left rotated.
// because node.left.left=black

// If the newly inserted node is under node.left, may cause right rotate. Assume the inserted nodes are
// in descending order, they will be continuously appending after the left most node which will rigger
// continuously right rotating.
if (isRed(node.left) && isRed(node.left.left)) {
node = rightRotate(node);

// after rotation, node.left = red, node.right = red
}

// 3. both left and right red

// if the node conducts right rotate, we got a node that its both left and right
// children are red.
if (isRed(node.left) && isRed(node.right)) {

// according to the rule, child node of red node should always be black
node.color = RED;

// for nodes of black color, they have no restriction of the color of child nodes.
node.left.color = BLACK;
node.right.color = BLACK;
}

// So, after a serial of adjustment, the tree will keep balanced finally.

return node;
}

/**
* Update the node bind the given key with new value.
*
* @param key
* @param value
* @return
*/
public void set(K key, V value) {
Node node = search(root, key);

if (node == null) {
throw new IllegalArgumentException(key + " Not Present!");
}

node.value = value;
}

/**
* Search the whole BST for the wanted node binding given key.
*
* @param key
* @return
*/
private Node search(K key) {
return search(root, key);
}

/**
* Search the specific node for the wanted node binding given key, usually called by
* <code>{@link #search(K)}</code>.
*
* @param node
* @param key
* @return
*/
private Node search(Node node, K key) {
if (node == null) {
return null;
}

// exactly the wanted node
if (key.compareTo(node.key) == 0) {
return node;
}
// wanted node on left branch
else if (key.compareTo(node.key) < 0) {
return search(node.left, key);
}

// wanted node on right branch

return search(node.right, key);
}

/**
* Search the whole BST for the node binding the smallest key.
*
* @param
*/
private Node getMin() {
return getMin(this.root);
}

/**
* Search under the given node for the node binding the smallest key, usually called by
* <code>{@link #getMin()}</code>.
*
* @param node
*/
private Node getMin(Node node) {
if (node.left == null) {
return node;
}

return getMin(node.left);
}

/**
* Delete the node binding the given key under the whole BST.
*
* @param key
* @return
*/
public V remove(K key) {
if (isEmpty()) {
return null;
}

Node node = search(root, key);

if (node != null) {
root = remove(root, key);

return node.value;
}

return null;
}

/**
* Delete the node binding the given key under the given node, usually called by
* <code>{@link #remove(K)}</code>.
*
* @param node
* @param key
* @return
*/
private Node remove(Node node, K key) {
if (node == null) {
return null;
}

// search left
if (key.compareTo(node.key) < 0) {
node.left = remove(node.left, key);
}
// search right
else if (key.compareTo(node.key) > 0) {
node.right = remove(node.right, key);
} else {
// exactly the current one is the wanted node

// 4 situations to be considered separately.

size--;

// 1. both empty
if (node.left == null && node.right == null) {
return null;
}

// 2. left empty
if (node.left == null) {
return node.right;
}

// 3. right empty
if (node.right == null) {
return node.left;
}

// 4. both non-empty

// Find the min node on right branch which should be a node without left branch.
Node successor = getMin(node.right);

// Remove the min node from its original position and serves as a successor of current
// node that going to be removed.
successor.right = remove(node.right, successor.key);

successor.left = node.left;

// unlink the removed node, so that the gc will quickly find it.
node.left = node.right = null;

node = successor;
}

// Then adjust node colors to make the tree balanced after deletion.

return keepBalanced(node);
}

public boolean contains(K key) {
return search(root, key) != null;
}

public int getSize() {
return size;
}


public boolean isEmpty() {
return size == 0;
}

public int getHeight() {
return getHeight(root);
}

private int getHeight(Node root) {
if (root == null) {
return 0;
}

int left = getHeight(root.left);
int right = getHeight(root.right);

return Math.max(left, right) + 1;
}

/**
* Verify current tree whether it's a qualified Binary Search Tree or not.
*
* @return
*/
public boolean isBST() {
ArrayList<K> keys = new ArrayList<>();

inOrderTraversal(root, keys);

for (int i = 1; i < keys.size(); i++) {
if (keys.get(i - 1).compareTo(keys.get(i)) > 0) {
return false;
}
}

return true;
}

private void inOrderTraversal(Node node, ArrayList<K> keys) {
if (node == null) {
return;
}

inOrderTraversal(node.left, keys);

keys.add(node.key);

inOrderTraversal(node.right, keys);
}

private class Node {
K key;
V value;

boolean color;

Node left;
Node right;

Node(K key, V value) {
this.key = key;
this.value = value;

this.color = RED;

this.left = null;
this.right = null;
}
}
}