- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathAVLTree.cs
399 lines (330 loc) · 13.1 KB
/
AVLTree.cs
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
usingSystem;
usingSystem.Collections.Generic;
namespaceDataStructures.Trees
{
/// <summary>
/// AVL Tree Data Structure.
/// </summary>
publicclassAVLTree<T>:BinarySearchTree<T>whereT:IComparable<T>
{
/// <summary>
/// Override the Root node accessors
/// </summary>
publicnewAVLTreeNode<T>Root
{
get{return(AVLTreeNode<T>)base.Root;}
internalset{base.Root=value;}
}
/// <summary>
/// CONSTRUCTOR.
/// Allows duplicates by default.
/// </summary>
publicAVLTree():base(){}
/// <summary>
/// CONSTRUCTOR.
/// If allowDuplictes is set to false, no duplicate items will be inserted.
/// </summary>
publicAVLTree(boolallowDuplicates):base(allowDuplicates){}
/// <summary>
/// Returns the height of a node.
/// </summary>
privateint_getNodeHeight(AVLTreeNode<T>node)
{
if(node==null)
return-1;
returnnode.Height;
}
/// <summary>
/// Updates the height of a node.
/// </summary>
privatevoid_updateNodeHeight(AVLTreeNode<T>node)
{
if(node==null)
return;
// height = 1 + the max between left and right children.
node.Height=1+Math.Max(_getNodeHeight(node.LeftChild),_getNodeHeight(node.RightChild));
}
/// <summary>
/// Updates the height of a node and it's parents' recursivley up to the root of the tree.
/// </summary>
privatevoid_updateHeightRecursive(AVLTreeNode<T>node)
{
if(node==null)
return;
// height = 1 + the max between left and right children.
node.Height=1+Math.Max(_getNodeHeight(node.LeftChild),_getNodeHeight(node.RightChild));
_updateHeightRecursive(node.Parent);
}
/// <summary>
/// Returns the AVL balance factor for a node.
/// </summary>
privateint_getBalanceFactor(AVLTreeNode<T>node)
{
if(node==null)
return-1;
return(_getNodeHeight(node.RightChild)-_getNodeHeight(node.LeftChild));
}
/// <summary>
/// Rotates a node to the left in the AVL tree.
/// </summary>
privatevoid_rotateLeftAt(AVLTreeNode<T>currentNode)
{
// We check the right child because it's going to be a pivot node for the rotation
if(currentNode==null||currentNode.HasRightChild==false)
return;
// Pivot on *right* child
AVLTreeNode<T>pivotNode=currentNode.RightChild;
// Parent of currentNode
AVLTreeNode<T>parent=currentNode.Parent;
// Check if currentNode is it's parent's left child.
boolisLeftChild=currentNode.IsLeftChild;
// Check if currentNode is the Root
boolisRootNode=(currentNode==this.Root);
// Perform the rotation
currentNode.RightChild=pivotNode.LeftChild;
pivotNode.LeftChild=currentNode;
// Update parents references
currentNode.Parent=pivotNode;
pivotNode.Parent=parent;
if(currentNode.HasRightChild)
currentNode.RightChild.Parent=currentNode;
//Update the entire tree's Root if necessary
if(isRootNode)
this.Root=pivotNode;
// Update the original parent's child node
if(isLeftChild)
parent.LeftChild=pivotNode;
elseif(parent!=null)
parent.RightChild=pivotNode;
// Update the AVL Heights of each node.
// _updateHeightRecursive(pivotNode);
_updateHeightRecursive(currentNode);
}
/// <summary>
/// Rotates a node to the right in the AVL tree.
/// </summary>
privatevoid_rotateRightAt(AVLTreeNode<T>currentNode)
{
// We check the right child because it's going to be a pivot node for the rotation
if(currentNode==null||currentNode.HasLeftChild==false)
return;
// Pivot on *left* child
varpivotNode=currentNode.LeftChild;
// Parent of currentNode
varparent=currentNode.Parent;
// Check if currentNode is it's parent's left child.
boolisLeftChild=currentNode.IsLeftChild;
// Check if currentNode is the Root
boolisRootNode=(currentNode==this.Root);
// Perform the rotation
currentNode.LeftChild=pivotNode.RightChild;
pivotNode.RightChild=currentNode;
// Update parents references
currentNode.Parent=pivotNode;
pivotNode.Parent=parent;
if(currentNode.HasLeftChild)
currentNode.LeftChild.Parent=currentNode;
// Update the entire tree's Root if necessary
if(isRootNode)
this.Root=pivotNode;
// Update the original parent's child node
if(isLeftChild)
parent.LeftChild=pivotNode;
elseif(parent!=null)
parent.RightChild=pivotNode;
// Update the AVL Heights of each node.
// _updateHeightRecursive(pivotNode);
_updateHeightRecursive(currentNode);
}
/// <summary>
/// Rebalances the tree around a node.
/// </summary>
privatevoid_rebalanceSubtreeTreeAt(AVLTreeNode<T>currentNode)
{
if(currentNode==null)
return;
intbalance=_getBalanceFactor(currentNode);
// Balance the tree only if the balance factor was less than -1 or greater than +1.
if(Math.Abs(balance)>=2)// -2 or 2; -3 or 3 ... etc
{
// if balance is a positive number: 2, 3 ... etc
// right subtree outweighs
if(balance>0)
{
intrightSubtreeBalance=_getBalanceFactor(currentNode.RightChild);
if(rightSubtreeBalance==0||rightSubtreeBalance==1)
{
// Rotate *LEFT* on current node
_rotateLeftAt(currentNode);
}
elseif(rightSubtreeBalance==-1)
{
// Rotate *RIGHT* on right child
_rotateRightAt(currentNode.RightChild);
// Rotate *LEFT* on current node
_rotateLeftAt(currentNode);
}
}
// if balance is a negative number: -2, -3 ... etc
// left subtree outweighs
else
{
intleftSubtreeBalance=_getBalanceFactor(currentNode.LeftChild);
if(leftSubtreeBalance==0||leftSubtreeBalance==1)
{
// Rotate *RIGHT* on current node
_rotateRightAt(currentNode);
}
elseif(leftSubtreeBalance==-1)
{
// Rotate *LEFT* on left child
_rotateLeftAt(currentNode.LeftChild);
// Rotate *RIGHT* on right child
_rotateRightAt(currentNode);
}
}
}
}
/// <summary>
/// Rebalances the whole tree around a node.
/// </summary>
privatevoid_rebalanceTreeAt(AVLTreeNode<T>node)
{
varcurrentNode=node;
while(currentNode!=null)
{
// Update this node's height value.
_updateNodeHeight(currentNode);
// Get left and right for comparisons
varleft=currentNode.LeftChild;
varright=currentNode.RightChild;
if(_getNodeHeight(left)>=2+_getNodeHeight(right))
{
if(currentNode.HasLeftChild&&_getNodeHeight(left.LeftChild)>=_getNodeHeight(left.RightChild))
{
_rotateRightAt(currentNode);
}
else
{
_rotateLeftAt(currentNode.LeftChild);
_rotateRightAt(currentNode);
}
}
elseif(_getNodeHeight(right)>=2+_getNodeHeight(left))
{
if(currentNode.HasRightChild&&_getNodeHeight(right.RightChild)>=_getNodeHeight(right.LeftChild))
{
_rotateLeftAt(currentNode);
}
else
{
_rotateRightAt(currentNode.RightChild);
_rotateLeftAt(currentNode);
}
}
currentNode=currentNode.Parent;
}
}
/// <summary>
/// Inserts an item to the tree.
/// </summary>
publicoverridevoidInsert(Titem)
{
// New node object
varnewNode=newAVLTreeNode<T>(){Value=item};
// Invoke the super BST insert node method.
// This insert node recursively starting from the root and checks for success status (related to allowDuplicates flag).
// The functions increments count on its own.
varsuccess=base._insertNode(newNode);
if(success==false&&_allowDuplicates==false)
thrownewInvalidOperationException("Tree does not allow inserting duplicate elements.");
// Rebalance the tree
_rebalanceTreeAt(newNode);
}
/// <summary>
/// Inserts an array of elements to the tree.
/// </summary>
publicoverridevoidInsert(T[]collection)
{
if(collection==null)
thrownewArgumentNullException();
if(collection.Length>0)
for(inti=0;i<collection.Length;++i)
this.Insert(collection[i]);
}
/// <summary>
/// Inserts a list of elements to the tree.
/// </summary>
publicoverridevoidInsert(List<T>collection)
{
if(collection==null)
thrownewArgumentNullException();
if(collection.Count>0)
for(inti=0;i<collection.Count;++i)
this.Insert(collection[i]);
}
/// <summary>
/// Removes an item fromt he tree
/// </summary>
publicoverridevoidRemove(Titem)
{
if(IsEmpty)
thrownewException("Tree is empty.");
// Get the node from the tree
varnode=(AVLTreeNode<T>)base._findNode(Root,item);
// Invoke the BST remove node method.
boolstatus=base._remove(node);
if(status==true)
{
// Rebalance the tree
// node.parent is actually the old parent of the node,
// which is the first potentially out-of-balance node.
_rebalanceTreeAt(node);
}
else
{
thrownewException("Item was not found.");
}
//// Update the node's parent height.
//_updateHeightRecursively(node.Parent);
//// Rebalance the tree
//var parent = node.Parent;
//while(parent != null)
//{
// _rebalanceSubtreeTreeAt(node.Parent);
//}
}
/// <summary>
/// Removes the min value from tree.
/// </summary>
publicoverridevoidRemoveMin()
{
if(IsEmpty)
thrownewException("Tree is empty.");
// Get the node from the tree
varnode=(AVLTreeNode<T>)base._findMinNode(Root);
// Invoke the BST remove node method.
base._remove(node);
// Rebalance the tree
// node.parent is actually the old parent of the node,
// which is the first potentially out-of-balance node.
_rebalanceTreeAt(node);
}
/// <summary>
/// Removes the max value from tree.
/// </summary>
publicoverridevoidRemoveMax()
{
if(IsEmpty)
thrownewException("Tree is empty.");
// Get the node from the tree
varnode=(AVLTreeNode<T>)base._findMaxNode(Root);
// Invoke the BST remove node method.
base._remove(node);
// Rebalance the tree
// node.parent is actually the old parent of the node,
// which is the first potentially out-of-balance node.
_rebalanceTreeAt(node);
}
}
}