-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAvlTree.js
executable file
·105 lines (87 loc) · 2.97 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
103
104
105
class AvlTree extends Tree {
insert(value) {
let node = super.insert(value);
let currentNode = node;
while (currentNode) {
this.balance(currentNode);
currentNode = currentNode.parent;
}
return node;
}
remove(value) {
super.remove(value);
this.balance(this.root);
}
balance(node) {
if (node == null) return;
if (node.balanceFactor > 1) {
if (node.left.balanceFactor > 0) {
this.rotateR(node);
} else if (node.left.balanceFactor < 0) {
this.rotateL(node.left);
this.rotateR(node);
}
// TEST, for delete
else {
this.rotateR(node);
}
} else if (node.balanceFactor < -1) {
if (node.right.balanceFactor < 0) {
this.rotateL(node);
} else if (node.right.balanceFactor > 0) {
this.rotateR(node.right);
this.rotateL(node);
}
// TEST, for delete
else {
this.rotateL(node);
}
}
}
rotateR(rootNode) {
// Detach left node from root node.
const leftNode = rootNode.left;
rootNode.setLeft(null);
// Make left node to be a child of rootNode's parent.
if (rootNode.parent) {
if (rootNode.parent.left == rootNode)
rootNode.parent.setLeft(leftNode);
else
rootNode.parent.setRight(leftNode);
} else if (rootNode === this.root) {
// If root node is root then make left node to be a new root.
this.root = leftNode;
}
// If left node has a right child then detach it and
// attach it as a left child for rootNode.
if (leftNode.right) {
rootNode.setLeft(leftNode.right);
}
// Attach rootNode to the right of leftNode.
leftNode.setRight(rootNode);
paintTree(this, "R-rotate at " + rootNode.value);
}
rotateL(rootNode) {
// Detach right node from root node.
const rightNode = rootNode.right;
rootNode.setRight(null);
// Make right node to be a child of rootNode's parent.
if (rootNode.parent) {
if (rootNode.parent.right == rootNode)
rootNode.parent.setRight(rightNode);
else
rootNode.parent.setLeft(rightNode);
} else if (rootNode === this.root) {
// If root node is root then make right node to be a new root.
this.root = rightNode;
}
// If right node has a left child then detach it and
// attach it as a right child for rootNode.
if (rightNode.left) {
rootNode.setRight(rightNode.left);
}
// Attach rootNode to the left of rightNode.
rightNode.setLeft(rootNode);
paintTree(this, "L-rotate at " + rootNode.value);
}
}