-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVLTree.js
89 lines (72 loc) · 1.56 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
function Node(data){
this.data = data;
this.height = 1;
this.left = null;
this.right = null;
}
function AVLTree(){
this.root = null;
}
function height(root){
if(!root)
return 0;
return root.height;
}
function getBalance(node){
return (height(node.left)-height(node.right));
}
function calculateHeight(node){
return (1 + Math.max(height(node.left), height(node.right)));
}
function leftRotate(node){
x = node.right;
t1 = x.left;
node.right = t1;
x.left = node;
node.height = calculateHeight(node);
x.height = calculateHeight(x);
return x;
}
function rightRotate(node){
x = node.left;
t1= node.right;
node.left = t1;
x.right = node;
node.height = calculateHeight(node);
x.height = calculateHeight(x);
return x;
}
function insert(root,data){
if(!root || !root.data){
root = new Node(data);
return root;
}
else{
if(data < root.data){
root.left = insert(root.left,data);
}
else if(data > root.data){
root.right = insert(root.right,data);
}
else{// no dupllicates
return root
}
}
root.height = calculateHeight(root);
var balance = getBalance(root);
if(balance > 1 && data< root.left.data){
root = rightRotate(root);
}
else if( balance > 1 && data >root.left.data){
root.left = leftRotate(root.left);
root = rightRotate(root);
}
else if(balance < 1 && data > root.right.data){
root = leftRotate(root);
}
else if(balance < 1 && data < root.right.data){
root.right = rightRotate(root.right);
root = leftRotate(root);
}
return root;
}