forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVLTree.cs
425 lines (377 loc) · 11.4 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
using System;
using System.Collections.Generic;
namespace DataStructures.AVLTree;
/// <summary>
/// A simple self-balancing binary tree.
/// </summary>
/// <remarks>
/// An AVL tree is a self-balancing binary search tree (BST) named after
/// its inventors: Adelson, Velsky, and Landis. It is the first self-
/// balancing BST invented. The primary property of an AVL tree is that
/// the height of both child subtrees for any node only differ by one.
/// Due to the balanced nature of the tree, its time complexities for
/// insertion, deletion, and search all have a worst-case time
/// complexity of O(log n). Which is an improvement over the worst-case
/// O(n) for a regular BST.
/// See https://en.wikipedia.org/wiki/AVL_tree for more information.
/// Visualizer: https://visualgo.net/en/bst.
/// </remarks>
/// <typeparam name="TKey">Type of key for the tree.</typeparam>
public class AvlTree<TKey>
{
/// <summary>
/// Gets the number of nodes in the tree.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Comparer to use when comparing key values.
/// </summary>
private readonly Comparer<TKey> comparer;
/// <summary>
/// Reference to the root node.
/// </summary>
private AvlTreeNode<TKey>? root;
/// <summary>
/// Initializes a new instance of the <see cref="AvlTree{TKey}"/>
/// class.
/// </summary>
public AvlTree()
{
comparer = Comparer<TKey>.Default;
}
/// <summary>
/// Initializes a new instance of the <see cref="AvlTree{TKey}"/>
/// class using the specified comparer.
/// </summary>
/// <param name="customComparer">
/// Comparer to use when comparing keys.
/// </param>
public AvlTree(Comparer<TKey> customComparer)
{
comparer = customComparer;
}
/// <summary>
/// Add a single node to the tree.
/// </summary>
/// <param name="key">Key value to add.</param>
public void Add(TKey key)
{
if (root is null)
{
root = new AvlTreeNode<TKey>(key);
}
else
{
root = Add(root, key);
}
Count++;
}
/// <summary>
/// Add multiple nodes to the tree.
/// </summary>
/// <param name="keys">Key values to add.</param>
public void AddRange(IEnumerable<TKey> keys)
{
foreach (var key in keys)
{
Add(key);
}
}
/// <summary>
/// Remove a node from the tree.
/// </summary>
/// <param name="key">Key value to remove.</param>
public void Remove(TKey key)
{
root = Remove(root, key);
Count--;
}
/// <summary>
/// Check if given node is in the tree.
/// </summary>
/// <param name="key">Key value to search for.</param>
/// <returns>Whether or not the node is in the tree.</returns>
public bool Contains(TKey key)
{
var node = root;
while (node is not null)
{
var compareResult = comparer.Compare(key, node.Key);
if (compareResult < 0)
{
node = node.Left;
}
else if (compareResult > 0)
{
node = node.Right;
}
else
{
return true;
}
}
return false;
}
/// <summary>
/// Get the minimum value in the tree.
/// </summary>
/// <returns>Minimum value in tree.</returns>
public TKey GetMin()
{
if (root is null)
{
throw new InvalidOperationException("AVL tree is empty.");
}
return GetMin(root).Key;
}
/// <summary>
/// Get the maximum value in the tree.
/// </summary>
/// <returns>Maximum value in tree.</returns>
public TKey GetMax()
{
if (root is null)
{
throw new InvalidOperationException("AVL tree is empty.");
}
return GetMax(root).Key;
}
/// <summary>
/// Get keys in order from smallest to largest as defined by the
/// comparer.
/// </summary>
/// <returns>Keys in tree in order from smallest to largest.</returns>
public IEnumerable<TKey> GetKeysInOrder()
{
List<TKey> result = new();
InOrderWalk(root);
return result;
void InOrderWalk(AvlTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
InOrderWalk(node.Left);
result.Add(node.Key);
InOrderWalk(node.Right);
}
}
/// <summary>
/// Get keys in the pre-order order.
/// </summary>
/// <returns>Keys in pre-order order.</returns>
public IEnumerable<TKey> GetKeysPreOrder()
{
var result = new List<TKey>();
PreOrderWalk(root);
return result;
void PreOrderWalk(AvlTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
result.Add(node.Key);
PreOrderWalk(node.Left);
PreOrderWalk(node.Right);
}
}
/// <summary>
/// Get keys in the post-order order.
/// </summary>
/// <returns>Keys in the post-order order.</returns>
public IEnumerable<TKey> GetKeysPostOrder()
{
var result = new List<TKey>();
PostOrderWalk(root);
return result;
void PostOrderWalk(AvlTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
PostOrderWalk(node.Left);
PostOrderWalk(node.Right);
result.Add(node.Key);
}
}
/// <summary>
/// Helper function to rebalance the tree so that all nodes have a
/// balance factor in the range [-1, 1].
/// </summary>
/// <param name="node">Node to rebalance.</param>
/// <returns>New node that has been rebalanced.</returns>
private static AvlTreeNode<TKey> Rebalance(AvlTreeNode<TKey> node)
{
if (node.BalanceFactor > 1)
{
if (node.Right!.BalanceFactor == -1)
{
node.Right = RotateRight(node.Right);
}
return RotateLeft(node);
}
if (node.BalanceFactor < -1)
{
if (node.Left!.BalanceFactor == 1)
{
node.Left = RotateLeft(node.Left);
}
return RotateRight(node);
}
return node;
}
/// <summary>
/// Perform a left (counter-clockwise) rotation.
/// </summary>
/// <param name="node">Node to rotate about.</param>
/// <returns>New node with rotation applied.</returns>
private static AvlTreeNode<TKey> RotateLeft(AvlTreeNode<TKey> node)
{
var temp1 = node;
var temp2 = node.Right!.Left;
node = node.Right;
node.Left = temp1;
node.Left.Right = temp2;
node.Left.UpdateBalanceFactor();
node.UpdateBalanceFactor();
return node;
}
/// <summary>
/// Perform a right (clockwise) rotation.
/// </summary>
/// <param name="node">Node to rotate about.</param>
/// <returns>New node with rotation applied.</returns>
private static AvlTreeNode<TKey> RotateRight(AvlTreeNode<TKey> node)
{
var temp1 = node;
var temp2 = node.Left!.Right;
node = node.Left;
node.Right = temp1;
node.Right.Left = temp2;
node.Right.UpdateBalanceFactor();
node.UpdateBalanceFactor();
return node;
}
/// <summary>
/// Helper function to get node instance with minimum key value
/// in the specified subtree.
/// </summary>
/// <param name="node">Node specifying root of subtree.</param>
/// <returns>Minimum value in node's subtree.</returns>
private static AvlTreeNode<TKey> GetMin(AvlTreeNode<TKey> node)
{
while (node.Left is not null)
{
node = node.Left;
}
return node;
}
/// <summary>
/// Helper function to get node instance with maximum key value
/// in the specified subtree.
/// </summary>
/// <param name="node">Node specifying root of subtree.</param>
/// <returns>Maximum value in node's subtree.</returns>
private static AvlTreeNode<TKey> GetMax(AvlTreeNode<TKey> node)
{
while (node.Right is not null)
{
node = node.Right;
}
return node;
}
/// <summary>
/// Recursively function to add a node to the tree.
/// </summary>
/// <param name="node">Node to check for null leaf.</param>
/// <param name="key">Key value to add.</param>
/// <returns>New node with key inserted.</returns>
private AvlTreeNode<TKey> Add(AvlTreeNode<TKey> node, TKey key)
{
// Regular binary search tree insertion
var compareResult = comparer.Compare(key, node.Key);
if (compareResult < 0)
{
if (node.Left is null)
{
var newNode = new AvlTreeNode<TKey>(key);
node.Left = newNode;
}
else
{
node.Left = Add(node.Left, key);
}
}
else if (compareResult > 0)
{
if (node.Right is null)
{
var newNode = new AvlTreeNode<TKey>(key);
node.Right = newNode;
}
else
{
node.Right = Add(node.Right, key);
}
}
else
{
throw new ArgumentException(
$"Key \"{key}\" already exists in AVL tree.");
}
// Check all of the new node's ancestors for inbalance and perform
// necessary rotations
node.UpdateBalanceFactor();
return Rebalance(node);
}
/// <summary>
/// Recursive function to remove node from tree.
/// </summary>
/// <param name="node">Node to check for key.</param>
/// <param name="key">Key value to remove.</param>
/// <returns>New node with key removed.</returns>
private AvlTreeNode<TKey>? Remove(AvlTreeNode<TKey>? node, TKey key)
{
if (node == null)
{
throw new KeyNotFoundException(
$"Key \"{key}\" is not in the AVL tree.");
}
// Normal binary search tree removal
var compareResult = comparer.Compare(key, node.Key);
if (compareResult < 0)
{
node.Left = Remove(node.Left, key);
}
else if (compareResult > 0)
{
node.Right = Remove(node.Right, key);
}
else
{
if (node.Left is null && node.Right is null)
{
return null;
}
if (node.Left is null)
{
var successor = GetMin(node.Right!);
node.Right = Remove(node.Right!, successor.Key);
node.Key = successor.Key;
}
else
{
var predecessor = GetMax(node.Left!);
node.Left = Remove(node.Left!, predecessor.Key);
node.Key = predecessor.Key;
}
}
// Check all of the removed node's ancestors for rebalance and
// perform necessary rotations.
node.UpdateBalanceFactor();
return Rebalance(node);
}
}