-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAVLTree.java
More file actions
83 lines (73 loc) · 2.26 KB
/
AVLTree.java
File metadata and controls
83 lines (73 loc) · 2.26 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
package dsa;
public class AVLTree {
private class AVLNode{
private int value;
private int height;
private AVLNode leftChild;
private AVLNode rightChild;
public AVLNode(int value){
this.value = value;
}
}
private AVLNode root;
public void insert(int value){
root = insert(root, value);
}
private AVLNode insert(AVLNode root, int value){
if(root == null) return new AVLNode(value);
if(value < root.value){
root.leftChild = insert(root.leftChild, value);
}
else if (value > root.value){
root.rightChild = insert(root.rightChild, value);
}
else{
}
setHeight(root);
return balance(root);
}
private AVLNode balance(AVLNode root){
if (isLeftHeavy(root)) {
if (balanceFactor(root.leftChild) < 0)
root.leftChild = leftRotate(root.leftChild);
return rightRotate(root);
}
else if (isRightheavy(root)) {
if (balanceFactor(root.rightChild) > 0)
root.rightChild = rightRotate(root.rightChild);
return leftRotate(root);
}
return root;
}
private AVLNode leftRotate(AVLNode root){
AVLNode newRoot = root.rightChild;
root.rightChild = newRoot.leftChild;
newRoot.leftChild = root;
setHeight(root);
setHeight(newRoot);
return newRoot;
}
private AVLNode rightRotate(AVLNode root){
AVLNode newRoot = root.leftChild;
root.leftChild = newRoot.rightChild;
newRoot.rightChild = root;
setHeight(root);
setHeight(newRoot);
return newRoot;
}
private boolean isLeftHeavy(AVLNode node){
return balanceFactor(node) > 1;
}
private boolean isRightheavy(AVLNode node){
return balanceFactor(node) < -1;
}
private int balanceFactor(AVLNode node){
return (node == null) ? 0 : height(node.leftChild) - height(node.rightChild);
}
private int height(AVLNode root){
return (root == null) ? -1 : root.height;
}
private void setHeight(AVLNode node){
node.height = Math.max(height(node.leftChild), height(node.rightChild)) + 1;
}
}