-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathAVLTree.java
More file actions
503 lines (464 loc) · 14.9 KB
/
AVLTree.java
File metadata and controls
503 lines (464 loc) · 14.9 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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
package dataStructures.avlTree;
import java.util.LinkedList;
import java.util.Queue;
/**
* Implementation of Adelson-Velsky, Landis (AVL) Tree.
*
* @param <T> generic type of object to be stored; must be comparable
* client methods:
* height(Node n)
* height(T key)
* root()
* insert(T key)
* delete(T key)
* search(T key)
* predecessor(T key)
* successor(T key)
* printInorder()
* printPreorder()
* printPostorder()
* printLevelOrder()
*/
public class AVLTree<T extends Comparable<T>> {
private Node<T> root;
/**
* Get root of tree.
*
* @return root
*/
public Node<T> root() {
return root;
}
/**
* Get height of node in avl tree.
*
* @param n node whose height is to be queried
* @return int value denoting height
*/
public int height(Node<T> n) {
return n == null ? -1 : n.getHeight();
}
/**
* Get height of node that holds the specified key
*
* @param key the key value of the node whose height is to be found
* @return int value representing height
*/
public int height(T key) {
return height(search(key));
}
/**
* Update height of node in avl tree for re-balancing.
*
* @param n node whose height is to be updated
*/
private void updateHeight(Node<T> n) {
n.setHeight(
1 + Math.max(
height(n.getLeft()),
height(n.getRight())
)
);
}
/**
* Get balance factor to check if height-balanced property is violated.
* Note: negative value means tree is right heavy,
* positive value means tree is left heavy,
* 0 means tree is balanced in weight.
*
* @param n check balance factor of node
* @return int value representing the balance factor
*/
private int getBalance(Node<T> n) {
return n == null ? 0 : height(n.getLeft()) - height(n.getRight());
}
/**
* Performs a right rotation on the specified node.
* Note that function should be called only if the
* node has a left child since it will be the
* new root.
*
* @param n node to perform right rotation on.
* @return the new root after rotation.
*/
private Node<T> rotateRight(Node<T> n) {
Node<T> newRoot = n.getLeft();
// this will become the left child of n after rotation
Node<T> newLeftSub = newRoot.getRight();
newRoot.setRight(n);
n.setLeft(newLeftSub);
newRoot.setParent(n.getParent());
updateHeight(n);
updateHeight(newRoot);
return newRoot;
}
/**
* Performs a left rotation on the specified node.
* Note that function should be called only if the
* node has a right child since it will be the
* new root.
*
* @param n node to perform left rotation on
* @return new root after rotation
*/
private Node<T> rotateLeft(Node<T> n) {
Node<T> newRoot = n.getRight();
// this will become the right child of n after rotation
Node<T> newRightSub = newRoot.getLeft();
newRoot.setLeft(n);
n.setRight(newRightSub);
newRoot.setParent(n.getParent());
updateHeight(n);
updateHeight(newRoot);
return newRoot;
}
/**
* Rebalances a node in the tree based on balance factor.
*
* @param n node to be rebalanced
* @return new root after rebalancing
*/
private Node<T> rebalance(Node<T> n) {
updateHeight(n);
int balance = getBalance(n);
if (balance < -1) { // right-heavy case
Node<T> rightChild = n.getRight();
Node<T> leftSubChild = rightChild.getLeft();
Node<T> rightSubChild = rightChild.getRight();
if (height(leftSubChild) > height(rightSubChild)) {
n.setRight(rotateRight(rightChild));
}
n = rotateLeft(n);
} else if (balance > 1) { // left-heavy case
Node<T> leftChild = n.getLeft();
Node<T> leftSubChild = leftChild.getLeft();
Node<T> rightSubChild = leftChild.getRight();
if (height(rightSubChild) > height(leftSubChild)) {
n.setLeft(rotateLeft(leftChild));
}
n = rotateRight(n);
}
return n;
}
/**
* Find the left-most child of the (sub)tree rooted at a specified node
*
* @param n tree is rooted at this node
* @return left-most node
*/
private Node<T> getMostLeft(Node<T> n) {
if (n.getLeft() == null) {
return n;
} else {
return getMostLeft(n.getLeft());
}
}
/**
* Find the right-most child of the (sub)tree rooted at a specified node
*
* @param n tree is rooted at this node
* @return right-most node
*/
private Node<T> getMostRight(Node<T> n) {
if (n.getRight() == null) {
return n;
} else {
return getMostRight(n.getRight());
}
}
/**
* Inserts a key into the tree
*
* @param key to be inserted
*/
public void insert(T key) {
root = insert(root, key);
}
/**
* Insert a key which will be wrapped in a node, into the tree rooted at a specified node.
* NOTE: ASSUMPTION THAT NO TWO NODES SHARE THE SAME KEY VALUE.
*
* @param node the (sub)tree rooted at node which the key will be inserted into
* @param key the key to insert
* @return the (new) node which the tree is rooted at after rebalancing
*/
private Node<T> insert(Node<T> node, T key) {
if (node == null) {
return new Node<>(key);
} else if (node.getKey().compareTo(key) < 0) {
node.setRight(insert(node.getRight(), key));
// note that insufficient to update parent in rotateLeft & rotateRight if still considered balanced
} else if (node.getKey().compareTo(key) > 0) {
node.setLeft(insert(node.getLeft(), key));
} else {
throw new RuntimeException("Duplicate key not supported!");
}
return rebalance(node);
}
/**
* Removes a key from the tree, if it exists
*
* @param key to be removed
*/
public void delete(T key) {
root = delete(root, key);
}
/**
* Delete a key from the avl tree rooted at a specified node.
* Find the node that holds the key and remove the node from the tree.
*
* @param node the (sub)tree rooted at node which the key will be deleted from
* @param key the key to remove
* @return the (new) root which the tree is rooted at after rebalancing
*/
private Node<T> delete(Node<T> node, T key) {
if (node == null) {
return null;
} else if (node.getKey().compareTo(key) < 0) {
node.setRight(delete(node.getRight(), key));
} else if (node.getKey().compareTo(key) > 0) {
node.setLeft(delete(node.getLeft(), key));
} else {
if (node.getLeft() == null || node.getRight() == null) { // case of 1 or 0 child
if (node.getLeft() == null && node.getRight() == null) { // 0-child case; just delete
node = null;
} else if (node.getRight() == null) {
Node<T> parentNode = node.getParent();
node.getLeft().setParent(parentNode);
node = node.getLeft();
} else {
Node<T> parentNode = node.getParent();
node.getRight().setParent(parentNode);
node = node.getRight();
}
} else { // 2-children case; successor replacement
Node<T> successor = getMostLeft(node.getRight());
node.setKey(successor.getKey());
// since this is a 2-children case, successor of deleted node have
// at most one child; right-child (else, it would continue going left)
node.setRight(delete(node.getRight(), successor.getKey()));
}
}
if (node != null) { // make sure it isn't the 0-child case
return rebalance(node);
}
return node; // null; case when nothing left
}
/**
* Search for a node with the specified key.
*
* @param key the key to look for
* @return node that has the specified key; null if not found
*/
public Node<T> search(T key) {
Node<T> curr = root;
while (curr != null) {
if (curr.getKey().compareTo(key) < 0) {
curr = curr.getRight();
} else if (curr.getKey().compareTo(key) > 0) {
curr = curr.getLeft();
} else {
return curr;
}
}
return null;
}
/**
* Search for the predecessor of a given key.
*
* @param key find predecessor of this key
* @return generic type value; null if key has no predecessor or tree is empty
*/
public T predecessor(T key) {
Node<T> curr = root;
if (curr == null) {
return null;
}
while (curr != null) {
if (curr.getKey().compareTo(key) == 0) {
break;
} else if (curr.getKey().compareTo(key) < 0) {
if (curr.getRight() == null) {
break;
}
curr = curr.getRight();
} else {
if (curr.getLeft() == null) {
break;
}
curr = curr.getLeft();
}
}
if (curr.getKey().compareTo(key) < 0) { // we are done
return curr.getKey();
}
return predecessor(curr); // pred could be an ancestor or child of curr node and hence handled separately
}
/**
* Find the key of the predecessor of a specified node that exists in the tree
* NOTE: the input node is assumed to be in the tree
*
* @param node node that exists in the tree
* @return key value; null if node has no predecessor
*/
private T predecessor(Node<T> node) {
Node<T> curr = node;
if (curr.getLeft() != null) { // has left-child
return getMostRight(curr.getLeft()).getKey();
} else { // so pred must be an ancestor
while (curr != null) {
if (curr.getKey().compareTo(node.getKey()) < 0) {
return curr.getKey();
}
curr = curr.getParent();
}
}
return null;
}
/**
* Search for the successor of a given key.
*
* @param key find successor of this key
* @return generic type value; null if key has no successor or tree is empty
*/
public T successor(T key) {
Node<T> curr = root;
if (curr == null) {
return null;
}
while (curr != null) {
if (curr.getKey().compareTo(key) == 0) {
break;
} else if (curr.getKey().compareTo(key) < 0) {
if (curr.getRight() == null) {
break;
}
curr = curr.getRight();
} else {
if (curr.getLeft() == null) {
break;
}
curr = curr.getLeft();
}
}
if (curr.getKey().compareTo(key) > 0) { // we are done
return curr.getKey();
}
return successor(curr); // same exp as in the pred fn
}
/**
* Find the key of the successor of a specified node that exists in the tree
* NOTE: the input node is assumed to be in the tree
*
* @param node node that exists in the tree
* @return key value; null if node has no successor
*/
private T successor(Node<T> node) {
Node<T> curr = node;
if (curr.getRight() != null) { // has right-child
return getMostLeft(curr.getRight()).getKey();
}
while (curr != null) {
if (curr.getKey().compareTo(node.getKey()) > 0) {
return curr.getKey();
}
curr = curr.getParent();
}
return null;
}
// ---------------------------------------------- NOTE ------------------------------------------------------------
// METHODS BELOW ARE NOT NECESSARY; JUST FOR VISUALISATION PURPOSES
/**
* prints in order traversal of the entire tree.
*/
public void printInorder() {
System.out.print("In-order: ");
printInorder(root);
System.out.println();
}
/**
* Prints out in-order traversal of tree rooted at node
*
* @param node node which the tree is rooted at
*/
private void printInorder(Node<T> node) {
if (node == null) {
return;
}
printInorder(node.getLeft());
System.out.print(node + " ");
printInorder(node.getRight());
}
/**
* prints pre-order traversal of the entire tree
*/
public void printPreorder() {
System.out.print("Pre-order: ");
printPreorder(root);
System.out.println();
}
/**
* Prints out pre-order traversal of tree rooted at node
*
* @param node node which the tree is rooted at
*/
private void printPreorder(Node<T> node) {
if (node == null) {
return;
}
System.out.print(node + " ");
printPreorder(node.getLeft());
printPreorder(node.getRight());
}
/**
* prints post-order traversal of the entire tree
*/
public void printPostorder() {
System.out.print("Post-order: ");
printPostorder(root);
System.out.println();
}
/**
* Prints out post-order traversal of tree rooted at node
*
* @param node node which the tree is rooted at
*/
private void printPostorder(Node<T> node) {
if (node == null) {
return;
}
printPostorder(node.getLeft());
printPostorder(node.getRight());
System.out.print(node + " ");
}
/**
* prints level-order traversal of the entire tree
*/
public void printLevelorder() {
System.out.print("Level-order: ");
printLevelorder(root);
System.out.println();
}
/**
* Prints out level-order traversal of tree rooted at node
*
* @param node node which the tree is rooted at
*/
private void printLevelorder(Node<T> node) {
if (node == null) {
return;
}
Queue<Node<T>> q = new LinkedList<>();
q.add(node);
while (!q.isEmpty()) {
Node<T> curr = q.poll();
System.out.print(curr.toString() + " ");
if (curr.getLeft() != null) {
q.add(curr.getLeft());
}
if (curr.getRight() != null) {
q.add(curr.getRight());
}
}
}
}