forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.cs
404 lines (359 loc) · 13.8 KB
/
BinarySearchTree.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
using System;
using System.Collections.Generic;
namespace DataStructures.BinarySearchTree
{
/// <summary>
/// An ordered tree with efficient insertion, removal, and lookup.
/// </summary>
/// <remarks>
/// A Binary Search Tree (BST) is a tree that satisfies the following properties:
/// <list type="bullet">
/// <item>All nodes in the tree contain two children, usually called Left and Right.</item>
/// <item>All nodes in the Left subtree contain keys that are less than the node's key.</item>
/// <item>All nodes in the Right subtree contain keys that are greater than the node's key.</item>
/// </list>
/// A BST will have an average complexity of O(log n) for insertion, removal, and lookup operations.
/// </remarks>
/// <typeparam name="TKey">Type of key for the BST. Keys must implement IComparable.</typeparam>
public class BinarySearchTree<TKey>
{
/// <summary>
/// Comparer to use when comparing node elements/keys.
/// </summary>
private readonly Comparer<TKey> comparer;
/// <summary>
/// The root of the BST.
/// </summary>
private BinarySearchTreeNode<TKey>? root;
public BinarySearchTree()
{
root = null;
Count = 0;
comparer = Comparer<TKey>.Default;
}
public BinarySearchTree(Comparer<TKey> customComparer)
{
root = null;
Count = 0;
comparer = customComparer;
}
/// <summary>
/// Gets the number nodes currently in the BST.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Insert a key into the BST.
/// </summary>
/// <param name="key">The key to insert.</param>
/// <exception cref="ArgumentException">
/// Thrown if key is already in BST.
/// </exception>
public void Add(TKey key)
{
if (root is null)
{
root = new BinarySearchTreeNode<TKey>(key);
}
else
{
Add(root, key);
}
Count++;
}
/// <summary>
/// Insert multiple keys into the BST.
/// Keys are inserted in the order they appear in the sequence.
/// </summary>
/// <param name="keys">Sequence of keys to insert.</param>
public void AddRange(IEnumerable<TKey> keys)
{
foreach (var key in keys)
{
Add(key);
}
}
/// <summary>
/// Find a node with the specified key.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>The node with the specified key if it exists, otherwise a default value is returned.</returns>
public BinarySearchTreeNode<TKey>? Search(TKey key) => Search(root, key);
/// <summary>
/// Checks if the specified key is in the BST.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>true if the key is in the BST, false otherwise.</returns>
public bool Contains(TKey key) => Search(root, key) is not null;
/// <summary>
/// Removes a node with a key that matches <paramref name="key" />.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>true if the removal was successful, false otherwise.</returns>
public bool Remove(TKey key)
{
if (root is null)
{
return false;
}
var result = Remove(root, root, key);
if (result)
{
Count--;
}
return result;
}
/// <summary>
/// Returns a node with the smallest key.
/// </summary>
/// <returns>The node if possible, a default value otherwise.</returns>
public BinarySearchTreeNode<TKey>? GetMin()
{
if (root is null)
{
return default;
}
return GetMin(root);
}
/// <summary>
/// Returns a node with the largest key.
/// </summary>
/// <returns>The node if possible, a default value otherwise.</returns>
public BinarySearchTreeNode<TKey>? GetMax()
{
if (root is null)
{
return default;
}
return GetMax(root);
}
/// <summary>
/// Returns all the keys in the BST, sorted In-Order.
/// </summary>
/// <returns>A list of keys in the BST.</returns>
public ICollection<TKey> GetKeysInOrder() => GetKeysInOrder(root);
/// <summary>
/// Returns all the keys in the BST, sorted Pre-Order.
/// </summary>
/// <returns>A list of keys in the BST.</returns>
public ICollection<TKey> GetKeysPreOrder() => GetKeysPreOrder(root);
/// <summary>
/// Returns all the keys in the BST, sorted Post-Order.
/// </summary>
/// <returns>A list of keys in the BST.</returns>
public ICollection<TKey> GetKeysPostOrder() => GetKeysPostOrder(root);
/// <summary>
/// Recursive method to add a key to the BST.
/// </summary>
/// <param name="node">Node to search from.</param>
/// <param name="key">Key to add.</param>
/// <exception cref="ArgumentException">
/// Thrown if key is already in the BST.
/// </exception>
private void Add(BinarySearchTreeNode<TKey> node, TKey key)
{
var compareResult = comparer.Compare(node.Key, key);
if (compareResult > 0)
{
if (node.Left is not null)
{
Add(node.Left, key);
}
else
{
var newNode = new BinarySearchTreeNode<TKey>(key);
node.Left = newNode;
}
}
else if (compareResult < 0)
{
if (node.Right is not null)
{
Add(node.Right, key);
}
else
{
var newNode = new BinarySearchTreeNode<TKey>(key);
node.Right = newNode;
}
}
// Key is already in tree.
else
{
throw new ArgumentException($"Key \"{key}\" already exists in tree!");
}
}
/// <summary>
/// Removes a node with the specified key from the BST.
/// </summary>
/// <param name="parent">The parent node of <paramref name="node" />.</param>
/// <param name="node">The node to check/search from.</param>
/// <param name="key">The key to remove.</param>
/// <returns>true if the operation was successful, false otherwise.</returns>
/// <remarks>
/// Removing a node from the BST can be split into three cases:
/// <br></br>
/// 0. The node to be removed has no children. In this case, the node can just be removed from the tree.
/// <br></br>
/// 1. The node to be removed has one child. In this case, the node's child is moved to the node's parent,
/// then the node is removed from the tree.
/// <br></br>
/// 2. The node to be removed has two children. In this case, we must find a suitable node among the children
/// subtrees to replace the node. This can be done with either the in-order predecessor or the in-order successor.
/// The in-order predecessor is the largest node in Left subtree, or the largest node that is still smaller then the
/// current node. The in-order successor is the smallest node in the Right subtree, or the smallest node that is
/// still larger than the current node. Either way, once this suitable node is found, remove it from the tree (it
/// should be either a case 1 or 2 node) and replace the node to be removed with this suitable node.
/// <br></br>
/// More information: https://en.wikipedia.org/wiki/Binary_search_tree#Deletion .
/// </remarks>
private bool Remove(BinarySearchTreeNode<TKey>? parent, BinarySearchTreeNode<TKey>? node, TKey key)
{
if (node is null || parent is null)
{
return false;
}
var compareResult = comparer.Compare(node.Key, key);
if (compareResult > 0)
{
return Remove(node, node.Left, key);
}
if (compareResult < 0)
{
return Remove(node, node.Right, key);
}
BinarySearchTreeNode<TKey>? replacementNode;
// Case 0: Node has no children.
// Case 1: Node has one child.
if (node.Left is null || node.Right is null)
{
replacementNode = node.Left ?? node.Right;
}
// Case 2: Node has two children. (This implementation uses the in-order predecessor to replace node.)
else
{
var predecessorNode = GetMax(node.Left);
Remove(root, root, predecessorNode.Key);
replacementNode = new BinarySearchTreeNode<TKey>(predecessorNode.Key)
{
Left = node.Left,
Right = node.Right,
};
}
// Replace the relevant node with a replacement found in the previous stages.
// Special case for replacing the root node.
if (node == root)
{
root = replacementNode;
}
else if (parent.Left == node)
{
parent.Left = replacementNode;
}
else
{
parent.Right = replacementNode;
}
return true;
}
/// <summary>
/// Recursive method to get node with largest key.
/// </summary>
/// <param name="node">Node to search from.</param>
/// <returns>Node with largest value.</returns>
private BinarySearchTreeNode<TKey> GetMax(BinarySearchTreeNode<TKey> node)
{
if (node.Right is null)
{
return node;
}
return GetMax(node.Right);
}
/// <summary>
/// Recursive method to get node with smallest key.
/// </summary>
/// <param name="node">Node to search from.</param>
/// <returns>Node with smallest value.</returns>
private BinarySearchTreeNode<TKey> GetMin(BinarySearchTreeNode<TKey> node)
{
if (node.Left is null)
{
return node;
}
return GetMin(node.Left);
}
/// <summary>
/// Recursive method to get a list with the keys sorted in in-order order.
/// </summary>
/// <param name="node">Node to traverse from.</param>
/// <returns>List of keys in in-order order.</returns>
private IList<TKey> GetKeysInOrder(BinarySearchTreeNode<TKey>? node)
{
if (node is null)
{
return new List<TKey>();
}
var result = new List<TKey>();
result.AddRange(GetKeysInOrder(node.Left));
result.Add(node.Key);
result.AddRange(GetKeysInOrder(node.Right));
return result;
}
/// <summary>
/// Recursive method to get a list with the keys sorted in pre-order order.
/// </summary>
/// <param name="node">Node to traverse from.</param>
/// <returns>List of keys in pre-order order.</returns>
private IList<TKey> GetKeysPreOrder(BinarySearchTreeNode<TKey>? node)
{
if (node is null)
{
return new List<TKey>();
}
var result = new List<TKey>();
result.Add(node.Key);
result.AddRange(GetKeysPreOrder(node.Left));
result.AddRange(GetKeysPreOrder(node.Right));
return result;
}
/// <summary>
/// Recursive method to get a list with the keys sorted in post-order order.
/// </summary>
/// <param name="node">Node to traverse from.</param>
/// <returns>List of keys in post-order order.</returns>
private IList<TKey> GetKeysPostOrder(BinarySearchTreeNode<TKey>? node)
{
if (node is null)
{
return new List<TKey>();
}
var result = new List<TKey>();
result.AddRange(GetKeysPostOrder(node.Left));
result.AddRange(GetKeysPostOrder(node.Right));
result.Add(node.Key);
return result;
}
/// <summary>
/// Recursive method to find a node with a matching key.
/// </summary>
/// <param name="node">Node to search from.</param>
/// <param name="key">Key to find.</param>
/// <returns>The node with the specified if it exists, a default value otherwise.</returns>
private BinarySearchTreeNode<TKey>? Search(BinarySearchTreeNode<TKey>? node, TKey key)
{
if (node is null)
{
return default;
}
var compareResult = comparer.Compare(node.Key, key);
if (compareResult > 0)
{
return Search(node.Left, key);
}
if (compareResult < 0)
{
return Search(node.Right, key);
}
return node;
}
}
}