-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathAVLTree.java
73 lines (53 loc) · 1.35 KB
/
AVLTree.java
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
package ds_011_balanced_trees;
public class AVLTree<T extends Comparable<T>> {
private class Node<G extends Comparable<G>> {
private G data;
private Node<G> left;
private Node<G> right;
public Node(G data) {
this.data = data;
this.left = null;
this.right = null;
}
public boolean isBalanced() {
return height() < 2;
}
public int height() {
return height(this);
}
private int height(Node<G> node) {
if(node == null) {
return -1;
}
return Integer.max(height(node.left), height(node.right)) + 1;
}
public void rightRotation() {
rightRotation(this);
}
private Node<G> rightRotation(Node<G> root) {
if(root.left == null) {
System.out.print("\tError: Unable to rightRotate: No Left Child!\n");
return null;
}
Node<G> newLeftChild = root.left.right;
Node<G> newRoot = root.left;
root.left = newLeftChild;
newRoot.right = root;
return newRoot;
}
public void leftRotation() {
leftRotation(this);
}
private Node<G> leftRotation(Node<G> root) {
if(root.right == null) {
System.out.print("\tError: Unable to leftRotate: No Right Child!\n");
return null;
}
Node<G> newRightChild = root.right.left;
Node<G> newRoot = root.right;
root.right = newRightChild;
newRoot.left = root;
return newRoot;
}
}
}