-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathavl.js
164 lines (130 loc) · 2.4 KB
/
avl.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// AVL Tree in C-like style
// Basics
function make_node(v)
{
var node = {
value : v,
height : 1,
left : null,
right : null
};
return node;
}
function max(a, b)
{
return a > b ? a : b;
}
function height(t)
{
return t ? t.height : 0;
}
function update_height(t)
{
t.height = max(height(t.left), height(t.right)) + 1;
}
function find_min(t)
{
if (t.left === null)
return t.value;
else
return find_min(t.left);
}
// Balancing tree
function left_rotate(x)
{
var y;
y = x.right;
x.right = y.left;
y.left = x;
update_height(x);
update_height(y);
return y;
}
function right_rotate(x)
{
var y;
y = x.left;
x.left = y.right;
y.right = x;
update_height(x);
update_height(y);
return y;
}
function balance(t)
{
if (height(t.left) - height(t.right) > 1) {
if (height(t.left.left) < height(t.left.right))
t.left = left_rotate(t.left);
t = right_rotate(t);
}
else if (height(t.left) - height(t.right) < -1) {
if (height(t.right.left) > height(t.right.right))
t.right = right_rotate(t.right);
t = left_rotate(t);
}
return t;
}
// Tree operations
function find(v, t)
{
if (t === null)
return false;
else if (v === t.value)
return true;
else if (v < t.value)
return find(v, t.left);
else
return find(v, t.right);
}
function insert(v, t)
{
if (t === null)
return make_node(v);
if (v < t.value)
t.left = insert(v, t.left);
else if (v > t.value)
t.right = insert(v, t.right);
else
return t;
update_height(t);
t = balance(t);
return t;
}
function remove(v, t)
{
if (t === null)
return null;
if (v === t.value) {
if (t.left === null) {
return t.right;
}
else if (t.right === null) {
return t.left;
}
else {
var min = find_min(t.right);
t.right = remove(min, t.right);
t.value = min;
}
}
else if (v < t.value)
t.left = remove(v, t.left);
else
t.right = remove(v, t.right);
update_height(t);
t = balance(t);
return t;
}
// Test
// function Test() {
// var avl = null; console.log(avl);
// avl = insert(1,avl); console.log(avl);
// avl = insert(2,avl); console.log(avl);
// avl = insert(3,avl); console.log(avl);
// console.log(find(1,avl));
// console.log(find(2,avl));
// console.log(find(3,avl));
// console.log(find(4,avl));
// avl = remove(2,avl); console.log(avl);
// }
// Test();