-
Notifications
You must be signed in to change notification settings - Fork 312
/
AVLTree.ts
78 lines (65 loc) · 2.04 KB
/
AVLTree.ts
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
import BinaryTreeNode from './BinaryTreeNode';
import BinarySearchTree from './BinarySearchTree';
/**
* An implementation of AVL tree based on BinarySearchTree.
*/
class AVLTree extends BinarySearchTree {
protected _insertImpl(
value: number,
node: BinaryTreeNode<number> | null,
): BinaryTreeNode<number> {
return this._balance(super._insertImpl(value, node));
}
protected _deleteImpl = (
value: number,
node: BinaryTreeNode<number> | null,
): BinaryTreeNode<number> | null => {
node = super._deleteImpl(value, node);
return node ? this._balance(node!) : node;
};
_balance(node: BinaryTreeNode<number>): BinaryTreeNode<number> {
// Helper function to calculate the balance of the node
const calcBalance = (node: BinaryTreeNode<number>): number =>
(node.left ? node.left!.height() + 1 : 0) -
(node.right ? node.right?.height() + 1 : 0);
// Check for whether the node is out-of-balance
const balance = calcBalance(node);
if (balance > 1) {
const leftBalance = calcBalance(node.left!);
if (leftBalance > 0) {
// LL case
node = this._rotateRight(node);
} else if (leftBalance < 0) {
// LR case
node.left = this._rotateLeft(node.left!);
node = this._rotateRight(node);
}
} else if (balance < -1) {
const rightBalance = calcBalance(node.right!);
if (rightBalance > 0) {
// RL case
node.right = this._rotateRight(node.right!);
node = this._rotateLeft(node);
} else if (rightBalance < 0) {
// RR case
node = this._rotateLeft(node);
}
}
return node;
}
_rotateRight(node: BinaryTreeNode<number>): BinaryTreeNode<number> {
const { left } = node;
const { right } = left!;
left!.right = node;
node.left = right;
return left!;
}
_rotateLeft(node: BinaryTreeNode<number>): BinaryTreeNode<number> {
const { right } = node;
const { left } = right!;
right!.left = node;
node.right = left;
return right!;
}
}
export default AVLTree;