-
Notifications
You must be signed in to change notification settings - Fork 293
/
BST.cs
435 lines (364 loc) · 10.6 KB
/
BST.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Advanced.Algorithms.DataStructures;
/// <summary>
/// A binary search tree implementation.
/// </summary>
public class Bst<T> : IEnumerable<T> where T : IComparable
{
public Bst()
{
}
/// <summary>
/// Initialize the BST with given sorted keys.
/// Time complexity: O(n).
/// </summary>
public Bst(IEnumerable<T> sortedCollection) : this()
{
BstHelpers.ValidateSortedCollection(sortedCollection);
var nodes = sortedCollection.Select(x => new BstNode<T>(null, x)).ToArray();
Root = (BstNode<T>)BstHelpers.ToBst(nodes);
BstHelpers.AssignCount(Root);
}
internal BstNode<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(n)
/// </summary>
public bool HasItem(T value)
{
if (Root == null) return false;
return Find(Root, value) != null;
}
/// <summary>
/// Time complexity: O(n)
/// </summary>
internal int GetHeight()
{
return GetHeight(Root);
}
//worst O(n) for unbalanced tree
private int GetHeight(BstNode<T> node)
{
if (node == null) return -1;
return Math.Max(GetHeight(node.Left), GetHeight(node.Right)) + 1;
}
internal BstNode<T> InsertAndReturnNewNode(T value)
{
if (Root == null)
{
Root = new BstNode<T>(null, value);
return Root;
}
var newNode = Insert(Root, value);
return newNode;
}
/// <summary>
/// Time complexity: O(n)
/// </summary>
public void Insert(T value)
{
if (Root == null)
{
Root = new BstNode<T>(null, value);
return;
}
var newNode = Insert(Root, value);
newNode.UpdateCounts(true);
}
//worst O(n) for unbalanced tree
private BstNode<T> Insert(BstNode<T> currentNode, T newNodeValue)
{
while (true)
{
var compareResult = currentNode.Value.CompareTo(newNodeValue);
//current node is less than new item
if (compareResult < 0)
{
//no right child
if (currentNode.Right != null)
{
currentNode = currentNode.Right;
continue;
}
//insert
currentNode.Right = new BstNode<T>(currentNode, newNodeValue);
return currentNode.Right;
}
//current node is greater than new node
if (compareResult > 0)
{
if (currentNode.Left == null)
{
//insert
currentNode.Left = new BstNode<T>(currentNode, newNodeValue);
return currentNode.Left;
}
currentNode = currentNode.Left;
}
else
{
throw new Exception("Item exists");
}
}
}
// <summary>
/// Time complexity: O(n)
/// </summary>
public int IndexOf(T item)
{
return Root.Position(item);
}
/// <summary>
/// Time complexity: O(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(n)
/// </summary>
public void Delete(T value)
{
if (Root == null) throw new Exception("Empty BST");
var deleted = Delete(Root, value);
deleted.UpdateCounts(true);
}
/// <summary>
/// Time complexity: O(n)
/// </summary>
public T RemoveAt(int index)
{
if (index < 0 || index >= Count) throw new ArgumentException("index");
var nodeToDelete = Root.KthSmallest(index) as BstNode<T>;
var deleted = Delete(nodeToDelete, nodeToDelete.Value);
deleted.UpdateCounts(true);
return nodeToDelete.Value;
}
//worst O(n) for unbalanced tree
private BstNode<T> Delete(BstNode<T> node, T value)
{
while (true)
{
if (node != null)
{
var compareResult = node.Value.CompareTo(value);
//node is less than the search value so move right to find the deletion node
if (compareResult < 0)
{
node = node.Right ?? throw new Exception("Item do not exist");
continue;
}
//node is less than the search value so move left to find the deletion node
if (compareResult > 0)
{
node = node.Left ?? throw new Exception("Item do not exist");
continue;
}
}
if (node == null) return null;
//node is a leaf node
if (node.IsLeaf)
{
DeleteLeaf(node);
return node;
}
//case one - right tree is null (move sub tree up)
if (node.Left != null && node.Right == null)
{
DeleteLeftNode(node);
return node;
}
//case two - left tree is null (move sub tree up)
if (node.Right != null && node.Left == null)
{
DeleteRightNode(node);
return node;
}
//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
var maxLeftNode = FindMax(node.Left);
node.Value = maxLeftNode.Value;
//delete left max node
node = node.Left;
value = maxLeftNode.Value;
}
}
private void DeleteLeaf(BstNode<T> node)
{
//if node is root
if (node.Parent == null)
Root = null;
//assign nodes parent.left/right to null
else if (node.IsLeftChild)
node.Parent.Left = null;
else
node.Parent.Right = null;
}
private void DeleteRightNode(BstNode<T> node)
{
//root
if (node.Parent == null)
{
Root.Right.Parent = null;
Root = Root.Right;
}
else
{
//node is left child of parent
if (node.IsLeftChild)
node.Parent.Left = node.Right;
//node is right child of parent
else
node.Parent.Right = node.Right;
node.Right.Parent = node.Parent;
}
}
private void DeleteLeftNode(BstNode<T> node)
{
//root
if (node.Parent == null)
{
Root.Left.Parent = null;
Root = Root.Left;
}
else
{
//node is left child of parent
if (node.IsLeftChild)
node.Parent.Left = node.Left;
//node is right child of parent
else
node.Parent.Right = node.Left;
node.Left.Parent = node.Parent;
}
}
/// <summary>
/// Time complexity: O(n)
/// </summary>
public T FindMax()
{
return FindMax(Root).Value;
}
private BstNode<T> FindMax(BstNode<T> node)
{
while (true)
{
if (node.Right == null) return node;
node = node.Right;
}
}
/// <summary>
/// Time complexity: O(n)
/// </summary>
public T FindMin()
{
return FindMin(Root).Value;
}
private BstNode<T> FindMin(BstNode<T> node)
{
while (true)
{
if (node.Left == null) return node;
node = node.Left;
}
}
//find the node with the given identifier among descendants of parent and parent
//uses pre-order traversal
//worst O(n) for unbalanced tree
internal BstNode<T> FindNode(T value)
{
return Find(Root, value);
}
//find the node with the given identifier among descendants of parent and parent
//uses pre-order traversal
//worst O(n) for unbalanced tree
private BstNode<T> Find(BstNode<T> parent, T value)
{
while (true)
{
if (parent == null) return null;
if (parent.Value.CompareTo(value) == 0) return parent;
var left = Find(parent.Left, value);
if (left != null) return left;
parent = parent.Right;
}
}
//find the node with the given identifier among descendants of parent and parent
//uses pre-order traversal
//O(log(n)) worst O(n) for unbalanced tree
private BstNodeBase<T> Find(T value)
{
return Root.Find(value).Item1;
}
/// <summary>
/// Get the next lower value to given value in this BST.
/// Time complexity: O(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(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;
}
/// <summary>
/// Descending enumerable.
/// </summary>
public IEnumerable<T> AsEnumerableDesc()
{
return GetEnumeratorDesc().AsEnumerable();
}
public IEnumerator<T> GetEnumeratorDesc()
{
return new BstEnumerator<T>(Root, false);
}
}
internal class BstNode<T> : BstNodeBase<T> where T : IComparable
{
internal BstNode(BstNode<T> parent, T value)
{
Parent = parent;
Value = value;
}
internal new BstNode<T> Parent
{
get => (BstNode<T>)base.Parent;
set => base.Parent = value;
}
internal new BstNode<T> Left
{
get => (BstNode<T>)base.Left;
set => base.Left = value;
}
internal new BstNode<T> Right
{
get => (BstNode<T>)base.Right;
set => base.Right = value;
}
}