-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAVLTree.java
More file actions
executable file
·100 lines (78 loc) · 2.94 KB
/
Copy pathAVLTree.java
File metadata and controls
executable file
·100 lines (78 loc) · 2.94 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
package com.codeWithArsalon.NonLinearDS;
public class AVLTree {
private class AVLNode {
private int height;
private int value;
private AVLNode leftChild;
private AVLNode rightChild;
public AVLNode(int value) {
this.value = value;
}
@Override
public String toString() {
return "value = " + value;
}
}
AVLNode root;
public void insert(int item){
root = insert(root, item); //set root field from object returned
}
private AVLNode insert(AVLNode root, int value){
if (root == null) //base condition
return new AVLNode(value);
if(value < root.value)
root.leftChild = insert(root.leftChild, value);
else
root.rightChild = insert(root.rightChild, value);
setHeight(root);
return balance(root); //returns + sets new root
}
private AVLNode balance (AVLNode root){
if(isLeftHeavy(root)) {
if(balanceFactor(root.leftChild) < 0){
root.leftChild = rotateLeft(root.leftChild); //returns new leftChild node
return rotateRight(root); //return new root
}
}
else if(isRightHeavy(root)) {
if (balanceFactor(root.rightChild) > 0) {
root.rightChild = rotateRight(root.rightChild); //returns new rightChild node
return rotateLeft(root); //return new root
}
}
return root; //tree is balanced
}
private AVLNode rotateRight(AVLNode root){
var newRoot = root.leftChild;
root.leftChild = newRoot.rightChild; // (left rotate)
newRoot.rightChild = root; //(right rotate)
setHeight(root); //update heights
setHeight(newRoot);
return newRoot;
}
private AVLNode rotateLeft(AVLNode root){
var newRoot = root.rightChild;
root.rightChild = newRoot.leftChild; //(right rotate)
newRoot.leftChild = root; //(left rotate)
setHeight(root); //update heights
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 : getHeight(node.leftChild) - getHeight(node.rightChild);
}
private void setHeight(AVLNode node){
node.height = Math.max(
getHeight(root.leftChild),
getHeight(root.rightChild) + 1);
}
private int getHeight(AVLNode node){
return (node == null) ? -1 : node.height;
}
}