-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathAvlTree.cs
617 lines (506 loc) · 16.5 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.DataStructures;
/// <summary>
/// An AVL tree implementation.
/// </summary>
public class AvlTree<T> : IEnumerable<T> where T : IComparable
{
private readonly Dictionary<T, BstNodeBase<T>> nodeLookUp;
/// <param name="enableNodeLookUp">
/// Enabling lookup will fasten deletion/insertion/exists operations
/// at the cost of additional space.
/// </param>
public AvlTree(bool enableNodeLookUp = false)
{
if (enableNodeLookUp) nodeLookUp = new Dictionary<T, BstNodeBase<T>>();
}
/// <summary>
/// Initialize the BST with given sorted keys.
/// Time complexity: O(n).
/// </summary>
/// <param name="sortedCollection">The initial sorted collection.</param>
/// <param name="enableNodeLookUp">
/// Enabling lookup will fasten deletion/insertion/exists operations
/// at the cost of additional space.
/// </param>
public AvlTree(IEnumerable<T> sortedCollection, bool enableNodeLookUp = false)
{
BstHelpers.ValidateSortedCollection(sortedCollection);
var nodes = sortedCollection.Select(x => new AvlTreeNode<T>(null, x)).ToArray();
Root = (AvlTreeNode<T>)BstHelpers.ToBst(nodes);
RecomputeHeight(Root);
BstHelpers.AssignCount(Root);
if (enableNodeLookUp) nodeLookUp = nodes.ToDictionary(x => x.Value, x => x as BstNodeBase<T>);
}
internal AvlTreeNode<T> Root { get; set; }
public int Count => Root == null ? 0 : Root.Count;
//Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return new BstEnumerator<T>(Root);
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public bool HasItem(T value)
{
if (Root == null) return false;
return Find(Root, value) != null;
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
internal int GetHeight()
{
if (Root == null)
return -1;
return Root.Height;
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public void Insert(T value)
{
if (Root == null)
{
Root = new AvlTreeNode<T>(null, value);
if (nodeLookUp != null) nodeLookUp[value] = Root;
return;
}
Insert(Root, value);
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
private void Insert(AvlTreeNode<T> node, T value)
{
var compareResult = node.Value.CompareTo(value);
//node is less than the value so move right for insertion
if (compareResult < 0)
{
if (node.Right == null)
{
node.Right = new AvlTreeNode<T>(node, value);
if (nodeLookUp != null) nodeLookUp[value] = node.Right;
}
else
{
Insert(node.Right, value);
}
}
//node is greater than the value so move left for insertion
else if (compareResult > 0)
{
if (node.Left == null)
{
node.Left = new AvlTreeNode<T>(node, value);
if (nodeLookUp != null) nodeLookUp[value] = node.Left;
}
else
{
Insert(node.Left, value);
}
}
else
{
throw new Exception("Item exists");
}
UpdateHeight(node);
Balance(node);
node.UpdateCounts();
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public int IndexOf(T item)
{
return Root.Position(item);
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public T ElementAt(int index)
{
if (index < 0 || index >= Count) throw new ArgumentNullException("index");
return Root.KthSmallest(index).Value;
}
/// <summary>
/// Time complexity: O(log(n)).
/// </summary>
public void Delete(T value)
{
if (Root == null) throw new Exception("Empty AVLTree");
Delete(Root, value);
if (nodeLookUp != null) nodeLookUp.Remove(value);
}
/// <summary>
/// Time complexity: O(log(n))
/// </summary>
public T RemoveAt(int index)
{
if (index < 0 || index >= Count) throw new ArgumentException("index");
var nodeToDelete = Root.KthSmallest(index) as AvlTreeNode<T>;
var nodeToBalance = Delete(nodeToDelete, nodeToDelete.Value);
while (nodeToBalance != null)
{
nodeToBalance.UpdateCounts();
UpdateHeight(nodeToBalance);
Balance(nodeToBalance);
nodeToBalance = nodeToBalance.Parent;
}
if (nodeLookUp != null) nodeLookUp.Remove(nodeToDelete.Value);
return nodeToDelete.Value;
}
private AvlTreeNode<T> Delete(AvlTreeNode<T> node, T value)
{
var baseCase = false;
var compareResult = node.Value.CompareTo(value);
//node is less than the search value so move right to find the deletion node
if (compareResult < 0)
{
if (node.Right == null) throw new Exception("Item do not exist");
Delete(node.Right, value);
}
//node is less than the search value so move left to find the deletion node
else if (compareResult > 0)
{
if (node.Left == null) throw new Exception("Item do not exist");
Delete(node.Left, value);
}
else
{
//node is a leaf node
if (node.IsLeaf)
{
//if node is root
if (node.Parent == null)
Root = null;
//assign nodes parent.left/right to null
else if (node.Parent.Left == node)
node.Parent.Left = null;
else
node.Parent.Right = null;
baseCase = true;
}
else
{
//case one - right tree is null (move sub tree up)
if (node.Left != null && node.Right == null)
{
//root
if (node.Parent == null)
{
Root.Left.Parent = null;
Root = Root.Left;
}
else
{
//node is left child of parent
if (node.Parent.Left == node)
node.Parent.Left = node.Left;
//node is right child of parent
else
node.Parent.Right = node.Left;
node.Left.Parent = node.Parent;
}
baseCase = true;
}
//case two - left tree is null (move sub tree up)
else if (node.Right != null && node.Left == null)
{
//root
if (node.Parent == null)
{
Root.Right.Parent = null;
Root = Root.Right;
}
else
{
//node is left child of parent
if (node.Parent.Left == node)
node.Parent.Left = node.Right;
//node is right child of parent
else
node.Parent.Right = node.Right;
node.Right.Parent = node.Parent;
}
baseCase = true;
}
//case three - two child trees
//replace the node value with maximum element of left subtree (left max node)
//and then delete the left max node
else
{
var maxLeftNode = FindMax(node.Left);
node.Value = maxLeftNode.Value;
if (nodeLookUp != null) nodeLookUp[node.Value] = node;
//delete left max node
Delete(node.Left, maxLeftNode.Value);
}
}
}
if (baseCase)
{
node.Parent.UpdateCounts();
UpdateHeight(node.Parent);
Balance(node.Parent);
return node.Parent;
}
node.UpdateCounts();
UpdateHeight(node);
Balance(node);
return node;
}
/// <summary>
/// Time complexity: O(log(n)).
/// </summary>
public T FindMax()
{
return FindMax(Root).Value;
}
private AvlTreeNode<T> FindMax(AvlTreeNode<T> node)
{
while (true)
{
if (node.Right == null) return node;
node = node.Right;
}
}
/// <summary>
/// Time complexity: O(log(n)).
/// </summary>
public T FindMin()
{
return FindMin(Root).Value;
}
private AvlTreeNode<T> FindMin(AvlTreeNode<T> node)
{
while (true)
{
if (node.Left == null) return node;
node = node.Left;
}
}
/// <summary>
/// Time complexity: O(log(n)).
/// </summary>
public bool Contains(T value)
{
if (Root == null) return false;
return Find(Root, value) != null;
}
//find the node with the given identifier among descendants of parent and parent
//uses pre-order traversal
private AvlTreeNode<T> Find(T value)
{
if (nodeLookUp != null) return nodeLookUp[value] as AvlTreeNode<T>;
return Root.Find(value).Item1 as AvlTreeNode<T>;
}
//find the node with the given identifier among descendants of parent and parent
//uses pre-order traversal
private AvlTreeNode<T> Find(AvlTreeNode<T> parent, T value)
{
if (parent == null) return null;
if (parent.Value.CompareTo(value) == 0) return parent;
var left = Find(parent.Left, value);
if (left != null) return left;
var right = Find(parent.Right, value);
return right;
}
private void Balance(AvlTreeNode<T> node)
{
if (node == null)
return;
if (node.Left == null && node.Right == null)
return;
var leftHeight = node.Left?.Height + 1 ?? 0;
var rightHeight = node.Right?.Height + 1 ?? 0;
var balanceFactor = leftHeight - rightHeight;
//tree is left heavy
//differance >=2 then do rotations
if (balanceFactor >= 2)
{
leftHeight = node.Left?.Left?.Height + 1 ?? 0;
rightHeight = node.Left?.Right?.Height + 1 ?? 0;
//left child is left heavy
if (leftHeight > rightHeight)
{
RightRotate(node);
}
//left child is right heavy
else
{
LeftRotate(node.Left);
RightRotate(node);
}
}
//tree is right heavy
//differance <=-2 then do rotations
else if (balanceFactor <= -2)
{
leftHeight = node.Right?.Left?.Height + 1 ?? 0;
rightHeight = node.Right?.Right?.Height + 1 ?? 0;
//right child is right heavy
if (rightHeight > leftHeight)
{
LeftRotate(node);
}
//right child is left heavy
else
{
RightRotate(node.Right);
LeftRotate(node);
}
}
}
private void RightRotate(AvlTreeNode<T> node)
{
var prevRoot = node;
var leftRightChild = prevRoot.Left.Right;
var newRoot = node.Left;
//make left child as root
prevRoot.Left.Parent = prevRoot.Parent;
if (prevRoot.Parent != null)
{
if (prevRoot.Parent.Left == prevRoot)
prevRoot.Parent.Left = prevRoot.Left;
else
prevRoot.Parent.Right = prevRoot.Left;
}
//move prev root as right child of current root
newRoot.Right = prevRoot;
prevRoot.Parent = newRoot;
//move right child of left child of prev root to left child of right child of new root
newRoot.Right.Left = leftRightChild;
if (newRoot.Right.Left != null) newRoot.Right.Left.Parent = newRoot.Right;
UpdateHeight(newRoot);
newRoot.Left.UpdateCounts();
newRoot.Right.UpdateCounts();
newRoot.UpdateCounts();
if (prevRoot == Root) Root = newRoot;
}
private void LeftRotate(AvlTreeNode<T> node)
{
var prevRoot = node;
var rightLeftChild = prevRoot.Right.Left;
var newRoot = node.Right;
//make right child as root
prevRoot.Right.Parent = prevRoot.Parent;
if (prevRoot.Parent != null)
{
if (prevRoot.Parent.Left == prevRoot)
prevRoot.Parent.Left = prevRoot.Right;
else
prevRoot.Parent.Right = prevRoot.Right;
}
//move prev root as left child of current root
newRoot.Left = prevRoot;
prevRoot.Parent = newRoot;
//move left child of right child of prev root to right child of left child of new root
newRoot.Left.Right = rightLeftChild;
if (newRoot.Left.Right != null) newRoot.Left.Right.Parent = newRoot.Left;
UpdateHeight(newRoot);
newRoot.Left.UpdateCounts();
newRoot.Right.UpdateCounts();
newRoot.UpdateCounts();
if (prevRoot == Root) Root = newRoot;
}
private void UpdateHeight(AvlTreeNode<T> node)
{
if (node == null) return;
if (node.Left != null)
node.Left.Height = Math.Max(node.Left.Left?.Height + 1 ?? 0,
node.Left.Right?.Height + 1 ?? 0);
if (node.Right != null)
node.Right.Height = Math.Max(node.Right.Left?.Height + 1 ?? 0,
node.Right.Right?.Height + 1 ?? 0);
node.Height = Math.Max(node.Left?.Height + 1 ?? 0,
node.Right?.Height + 1 ?? 0);
}
private void RecomputeHeight(AvlTreeNode<T> node)
{
if (node == null) return;
RecomputeHeight(node.Left);
RecomputeHeight(node.Right);
UpdateHeight(node);
}
/// <summary>
/// Get the next lower value to given value in this BST.
/// Time complexity: O(log(n))
/// </summary>
public T NextLower(T value)
{
var node = Find(value);
if (node == null) return default;
var next = node.NextLower();
return next != null ? next.Value : default;
}
/// <summary>
/// Get the next higher value to given value in this BST.
/// Time complexity: O(log(n))
/// </summary>
public T NextHigher(T value)
{
var node = Find(value);
if (node == null) return default;
var next = node.NextHigher();
return next != null ? next.Value : default;
}
internal void Swap(T value1, T value2)
{
var node1 = Find(value1);
var node2 = Find(value2);
if (node1 == null || node2 == null) throw new Exception("Value1, Value2 or both was not found in this BST.");
var tmp = node1.Value;
node1.Value = node2.Value;
node2.Value = tmp;
if (nodeLookUp != null)
{
nodeLookUp[node1.Value] = node1;
nodeLookUp[node2.Value] = node2;
}
}
/// <summary>
/// Descending enumerable.
/// </summary>
public IEnumerable<T> AsEnumerableDesc()
{
return GetEnumeratorDesc().AsEnumerable();
}
public IEnumerator<T> GetEnumeratorDesc()
{
return new BstEnumerator<T>(Root, false);
}
}
internal class AvlTreeNode<T> : BstNodeBase<T> where T : IComparable
{
internal AvlTreeNode(AvlTreeNode<T> parent, T value)
{
Parent = parent;
Value = value;
Height = 0;
}
internal new AvlTreeNode<T> Parent
{
get => (AvlTreeNode<T>)base.Parent;
set => base.Parent = value;
}
internal new AvlTreeNode<T> Left
{
get => (AvlTreeNode<T>)base.Left;
set => base.Left = value;
}
internal new AvlTreeNode<T> Right
{
get => (AvlTreeNode<T>)base.Right;
set => base.Right = value;
}
internal int Height { get; set; }
}