forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVLTree.js
102 lines (92 loc) · 2.34 KB
/
AVLTree.js
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
class AVLTree {
constructor() {
// Initialising the root element to null.
this.root = null;
}
getBalanceFactor(root) {
return this.getHeight(root.left) - this.getHeight(root.right);
}
getHeight(root) {
let height = 0;
if (root === null || typeof root == "undefined") {
height = -1;
} else {
height = Math.max(this.getHeight(root.left), this.getHeight(root.right)) + 1;
}
return height;
}
insert(data) {
let node = new this.Node(data);
// Checking if the tree is empty
if (this.root === null) {
// Insert the first element as this.root = node;
} else {
insertHelper(this, this.root, node);
}
}
inOrder() {
inOrderHelper(this.root);
}
}
AVLTree.prototype.Node = class {
constructor(data, left = null, right = null) {
this.data = data;
this.left = left;
this.right = right;
}
};
function insertHelper(self, root, node) {
(root === null) {
root = node;
} else if (node.data < root.data) {
// Go left
root.left = insertHelper(self, root.left, node)
// Check for balance factor and perform the appropriate rotation
if (root.left !== null && self.getBalanceFactor(root) > 1) {
if (node.data > root.left.data) {
root = rotationLL(root);
} else {
root = rotationLR(root);
}
}
} else if (node.data > root.data) {
// Go Right
right = insertHelper(self, root.right, node);
// Check for balance factor and perform appropriate rotation
if (root.right !== null && self.getBalanceFactor(root) < -1) {
if (node.data > root.right.data) {
root = rotationRR(root);
} else {
root = rotationRL(root);
}
}
}
return root;
}
function inOrderHelper(root) {
if (root !== null) {
inOrderHelper(root.left);
console.log(root.data);
inOrderHelper(root.right);
}
}
function rotationLL(node) {
let tmp = node.left;
node.left = tmp.right;
tmp.right = node;
return tmp;
}
function rotationRR(node) {
let tmp = node.right;
node.right = tmp.left;
tmp.left = node;
return tmp;
}
function rotationLR(node) {
node.left = rotationRR(node.left);
return rotationLL(node);
}
function rotationRL(node) {
node.right = rotationLL(node.right);
return rotationRR(node);
}