-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavl-tree.js
40 lines (34 loc) · 913 Bytes
/
avl-tree.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
import BinarySearchTree, { Node } from './binary-search-tree';
const BALANCE = {
BALANCED: 0,
UNBALANCED_LEFT: 1,
UNBALANCED_RIGHT: 2,
SLIGHTLY_UNBALANCED_LEFT: 3,
SLIGHTLY_UNBALANCED_RIGHT: 4,
};
export default class AVLTree extends BinarySearchTree {
constructor(compareFunc) {
super(compareFunc);
}
getNodeHeight(node) {
if (node === null) {
return -1;
}
return 1 + Math.max(this.getNodeHeight(node.left), this.getNodeHeight(node.right));
}
getBalance(node) {
const height = this.getNodeHeight(node.left) - this.getNodeHeight(node.right);
switch (height) {
case -2:
return BALANCE.UNBALANCED_RIGHT;
case -1:
return BALANCE.SLIGHTLY_UNBALANCED_RIGHT;
case 2:
return BALANCE.UNBALANCED_LEFT;
case 1:
return BALANCE.SLIGHTLY_UNBALANCED_LEFT;
default:
return BALANCE.BALANCED;
}
}
}