forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearchTreeMap.cs
841 lines (694 loc) · 25.2 KB
/
BinarySearchTreeMap.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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
using System;
using System.Collections;
using System.Collections.Generic;
using DataStructures.Common;
namespace DataStructures.Trees
{
/// <summary>
/// Implements a generic Binary Search Tree Map data structure.
/// </summary>
public class BinarySearchTreeMap<TKey, TValue> : IBinarySearchTree<TKey, TValue> where TKey : IComparable<TKey>
{
/// <summary>
/// Specifies the mode of travelling through the tree.
/// </summary>
public enum TraversalMode
{
InOrder = 0,
PreOrder = 1,
PostOrder = 2
}
/// <summary>
/// TREE INSTANCE VARIABLES
/// </summary>
protected int _count { get; set; }
protected bool _allowDuplicates { get; set; }
protected virtual BSTMapNode<TKey, TValue> _root { get; set; }
public virtual BSTMapNode<TKey, TValue> Root
{
get { return this._root; }
internal set { this._root = value; }
}
/// <summary>
/// CONSTRUCTOR.
/// Allows duplicates by default.
/// </summary>
public BinarySearchTreeMap()
{
_count = 0;
_allowDuplicates = true;
Root = null;
}
/// <summary>
/// CONSTRUCTOR.
/// If allowDuplictes is set to false, no duplicate items will be inserted.
/// </summary>
public BinarySearchTreeMap(bool allowDuplicates)
{
_count = 0;
_allowDuplicates = allowDuplicates;
Root = null;
}
/// <summary>
/// Calculates the tree height from a specific node, recursively.
/// Time-complexity: O(n), where n = number of nodes.
/// </summary>
protected virtual int _getTreeHeight(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return 0;
// Is leaf node
if (node.IsLeafNode)
return 1;
// Has two children
if (node.ChildrenCount == 2)
return (1 + Math.Max(_getTreeHeight(node.LeftChild), _getTreeHeight(node.RightChild)));
// Has only left
if (node.HasLeftChild)
return (1 + _getTreeHeight(node.LeftChild));
// Has only right
return (1 + _getTreeHeight(node.RightChild));
}
/// <summary>
/// Inserts a new node to the tree.
/// </summary>
protected virtual bool _insertNode(BSTMapNode<TKey, TValue> newNode)
{
// Handle empty trees
if (this.Root == null)
{
Root = newNode;
_count++;
return true;
}
if (newNode.Parent == null)
newNode.Parent = this.Root;
// Check for value equality and whether inserting duplicates is allowed
if (_allowDuplicates == false && newNode.Parent.Key.IsEqualTo(newNode.Key))
{
return false;
}
// Go Left
if (newNode.Parent.Key.IsGreaterThan(newNode.Key)) // newNode < parent
{
if (newNode.Parent.HasLeftChild == false)
{
newNode.Parent.LeftChild = newNode;
// Increment count.
_count++;
return true;
}
newNode.Parent = newNode.Parent.LeftChild;
return _insertNode(newNode);
}
// Go Right
if (newNode.Parent.HasRightChild == false)
{
newNode.Parent.RightChild = newNode;
// Increment count.
_count++;
return true;
}
newNode.Parent = newNode.Parent.RightChild;
return _insertNode(newNode);
}
/// <summary>
/// Replaces the node's value from it's parent node object with the newValue.
/// Used in the recusive _remove function.
/// </summary>
protected virtual void _replaceNodeInParent(BSTMapNode<TKey, TValue> node, BSTMapNode<TKey, TValue> newNode = null)
{
if (node.Parent != null)
{
if (node.IsLeftChild)
node.Parent.LeftChild = newNode;
else
node.Parent.RightChild = newNode;
}
if (newNode != null)
newNode.Parent = node.Parent;
}
/// <summary>
/// Remove the specified node.
/// </summary>
protected virtual bool _remove(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return false;
var parent = node.Parent;
if (node.ChildrenCount == 2) // if both children are present
{
var successor = node.RightChild;
node.Key = successor.Key;
node.Value = successor.Value;
return (true && _remove(successor));
}
if (node.HasLeftChild) // if the node has only a LEFT child
{
_replaceNodeInParent(node, node.LeftChild);
_count--;
}
else if (node.HasRightChild) // if the node has only a RIGHT child
{
_replaceNodeInParent(node, node.RightChild);
_count--;
}
else //this node has no children
{
_replaceNodeInParent(node, null);
_count--;
}
return true;
}
/// <summary>
/// Finds a node inside another node's subtrees, given it's value.
/// </summary>
protected virtual BSTMapNode<TKey, TValue> _findNode(BSTMapNode<TKey, TValue> currentNode, TKey key)
{
if (currentNode == null)
return currentNode;
if (key.IsEqualTo(currentNode.Key))
{
return currentNode;
}
if (currentNode.HasLeftChild && key.IsLessThan(currentNode.Key))
{
return _findNode(currentNode.LeftChild, key);
}
if (currentNode.HasRightChild && key.IsGreaterThan(currentNode.Key))
{
return _findNode(currentNode.RightChild, key);
}
// Return-functions-fix
return null;
}
/// <summary>
/// Returns the min-node in a subtree.
/// Used in the recusive _remove function.
/// </summary>
protected virtual BSTMapNode<TKey, TValue> _findMinNode(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return node;
var currentNode = node;
while (currentNode.HasLeftChild)
currentNode = currentNode.LeftChild;
return currentNode;
}
/// <summary>
/// Returns the max-node in a subtree.
/// Used in the recusive _remove function.
/// </summary>
protected virtual BSTMapNode<TKey, TValue> _findMaxNode(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return node;
var currentNode = node;
while (currentNode.HasRightChild)
currentNode = currentNode.RightChild;
return currentNode;
}
/// <summary>
/// Finds the next smaller node in value compared to the specified node.
/// </summary>
protected virtual BSTMapNode<TKey, TValue> _findNextSmaller(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return node;
if (node.HasLeftChild)
return _findMaxNode(node.LeftChild);
var currentNode = node;
while (currentNode.Parent != null && currentNode.IsLeftChild)
currentNode = currentNode.Parent;
return currentNode.Parent;
}
/// <summary>
/// Finds the next larger node in value compared to the specified node.
/// </summary>
protected virtual BSTMapNode<TKey, TValue> _findNextLarger(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return node;
if (node.HasRightChild)
return _findMinNode(node.RightChild);
var currentNode = node;
while (currentNode.Parent != null && currentNode.IsRightChild)
currentNode = currentNode.Parent;
return currentNode.Parent;
}
/// <summary>
/// A recursive private method. Used in the public FindAll(predicate) functions.
/// Implements in-order traversal to find all the matching elements in a subtree.
/// </summary>
protected virtual void _findAll(BSTMapNode<TKey, TValue> currentNode, Predicate<TKey> match, ref List<KeyValuePair<TKey, TValue>> list)
{
if (currentNode == null)
return;
// call the left child
_findAll(currentNode.LeftChild, match, ref list);
if (match(currentNode.Key)) // match
list.Add(new KeyValuePair<TKey, TValue>(currentNode.Key, currentNode.Value));
// call the right child
_findAll(currentNode.RightChild, match, ref list);
}
/// <summary>
/// In-order traversal of the subtrees of a node. Returns every node it vists.
/// </summary>
protected virtual void _inOrderTraverse(BSTMapNode<TKey, TValue> currentNode, ref List<KeyValuePair<TKey, TValue>> list)
{
if (currentNode == null)
return;
// call the left child
_inOrderTraverse(currentNode.LeftChild, ref list);
// visit node
list.Add(new KeyValuePair<TKey, TValue>(currentNode.Key, currentNode.Value));
// call the right child
_inOrderTraverse(currentNode.RightChild, ref list);
}
/// <summary>
/// Return the number of elements in this tree
/// </summary>
public virtual int Count
{
get { return _count; }
}
/// <summary>
/// Checks if tree is empty.
/// </summary>
public virtual bool IsEmpty
{
get { return (_count == 0); }
}
/// <summary>
/// Returns the height of the tree.
/// Time-complexity: O(n), where n = number of nodes.
/// </summary>
public virtual int Height
{
get
{
if (IsEmpty)
return 0;
var currentNode = Root;
return _getTreeHeight(currentNode);
}
}
public virtual bool AllowsDuplicates
{
get { return _allowDuplicates; }
}
/// <summary>
/// Inserts a key-value pair to the tree
/// </summary>
public virtual void Insert(TKey key, TValue value)
{
var newNode = new BSTMapNode<TKey, TValue>(key, value);
// Insert node recursively starting from the root. check for success status.
var success = _insertNode(newNode);
if (success == false && _allowDuplicates == false)
throw new InvalidOperationException("Tree does not allow inserting duplicate elements.");
}
/// <summary>
/// Inserts a key-value pair to the tree
/// </summary>
public virtual void Insert(KeyValuePair<TKey, TValue> keyValuePair)
{
Insert(keyValuePair.Key, keyValuePair.Value);
}
/// <summary>
/// Inserts an array of elements to the tree.
/// </summary>
public virtual void Insert(TKey[] collection)
{
if (collection == null)
throw new ArgumentNullException();
if (collection.Length > 0)
{
for (int i = 0; i < collection.Length; ++i)
{
this.Insert(collection[i], default(TValue));
}
}
}
/// <summary>
/// Inserts an array of key-value pairs to the tree.
/// </summary>
public virtual void Insert(KeyValuePair<TKey, TValue>[] collection)
{
if (collection == null)
throw new ArgumentNullException();
if (collection.Length > 0)
{
for (int i = 0; i < collection.Length; ++i)
{
this.Insert(collection[i].Key, collection[i].Value);
}
}
}
/// <summary>
/// Inserts a list of elements to the tree.
/// </summary>
public virtual void Insert(List<TKey> collection)
{
if (collection == null)
throw new ArgumentNullException();
if (collection.Count > 0)
{
for (int i = 0; i < collection.Count; ++i)
{
this.Insert(collection[i], default(TValue));
}
}
}
/// <summary>
/// Inserts a list of elements to the tree.
/// </summary>
public virtual void Insert(List<KeyValuePair<TKey, TValue>> collection)
{
if (collection == null)
throw new ArgumentNullException();
if (collection.Count > 0)
{
for (int i = 0; i < collection.Count; ++i)
{
this.Insert(collection[i].Key, collection[i].Value);
}
}
}
/// <summary>
/// Updates the node of a specific key with a new value.
/// </summary>
public virtual void Update(TKey key, TValue newValue)
{
if (IsEmpty)
throw new Exception("Tree is empty.");
var node = _findNode(Root, key);
if (node == null)
throw new KeyNotFoundException("Key doesn't exist in tree.");
node.Value = newValue;
}
/// <summary>
/// Deletes an element from the tree with a specified key.
/// </summary>
public virtual void Remove(TKey key)
{
if (IsEmpty)
throw new Exception("Tree is empty.");
var node = _findNode(Root, key);
if (node == null)
throw new KeyNotFoundException("Key doesn't exist in tree.");
_remove(node);
}
/// <summary>
/// Removes the min value from tree.
/// </summary>
public virtual void RemoveMin()
{
if (IsEmpty)
throw new Exception("Tree is empty.");
var node = _findMinNode(Root);
_remove(node);
}
/// <summary>
/// Removes the max value from tree.
/// </summary>
public virtual void RemoveMax()
{
if (IsEmpty)
throw new Exception("Tree is empty.");
var node = _findMaxNode(Root);
_remove(node);
}
/// <summary>
/// Clears all elements from tree.
/// </summary>
public virtual void Clear()
{
Root = null;
_count = 0;
}
/// <summary>
/// Checks for the existence of an item
/// </summary>
public virtual bool Contains(TKey key)
{
return (_findNode(_root, key) != null);
}
/// <summary>
/// Finds the minimum in tree
/// </summary>
/// <returns>Min</returns>
public virtual KeyValuePair<TKey, TValue> FindMin()
{
if (IsEmpty)
throw new Exception("Tree is empty.");
var minNode =_findMinNode(Root);
return new KeyValuePair<TKey, TValue>(minNode.Key, minNode.Value);
}
/// <summary>
/// Finds the next smaller element in tree, compared to the specified item.
/// </summary>
public virtual KeyValuePair<TKey, TValue> FindNextSmaller(TKey key)
{
var node = _findNode(Root, key);
var nextSmaller = _findNextSmaller(node);
if (nextSmaller == null)
throw new Exception("Item was not found.");
return new KeyValuePair<TKey, TValue>(nextSmaller.Key, nextSmaller.Value);
}
/// <summary>
/// Finds the next larger element in tree, compared to the specified item.
/// </summary>
public virtual KeyValuePair<TKey, TValue> FindNextLarger(TKey item)
{
var node = _findNode(Root, item);
var nextLarger = _findNextLarger(node);
if (nextLarger == null)
throw new Exception("Item was not found.");
return new KeyValuePair<TKey, TValue>(nextLarger.Key, nextLarger.Value);
}
/// <summary>
/// Finds the maximum in tree
/// </summary>
/// <returns>Max</returns>
public virtual KeyValuePair<TKey, TValue> FindMax()
{
if (IsEmpty)
throw new Exception("Tree is empty.");
var maxNode = _findMaxNode(Root);
return new KeyValuePair<TKey, TValue>(maxNode.Key, maxNode.Value);
}
/// <summary>
/// Find the item in the tree. Throws an exception if not found.
/// </summary>
/// <param name="item">Item to find.</param>
/// <returns>Item.</returns>
public virtual KeyValuePair<TKey, TValue> Find(TKey key)
{
if (IsEmpty)
throw new Exception("Tree is empty.");
var node = _findNode(Root, key);
if (node != null)
return new KeyValuePair<TKey, TValue>(node.Key, node.Value);
throw new KeyNotFoundException("Item was not found.");
}
/// <summary>
/// Given a predicate function, find all the elements that match it.
/// </summary>
/// <param name="searchPredicate">The search predicate</param>
/// <returns>ArrayList<T> of elements.</returns>
public virtual IEnumerable<KeyValuePair<TKey, TValue>> FindAll(Predicate<TKey> searchPredicate)
{
var list = new List<KeyValuePair<TKey, TValue>>();
_findAll(Root, searchPredicate, ref list);
return list;
}
/// <summary>
/// Returns an array of nodes' values.
/// </summary>
/// <returns>The array.</returns>
public virtual KeyValuePair<TKey, TValue>[] ToArray()
{
return this.ToList().ToArray();
}
/// <summary>
/// Returns a list of the nodes' value.
/// </summary>
public virtual List<KeyValuePair<TKey, TValue>> ToList()
{
var list = new List<KeyValuePair<TKey, TValue>>();
_inOrderTraverse(Root, ref list);
return list;
}
/*********************************************************************/
/// <summary>
/// Returns an enumerator that visits node in the order: parent, left child, right child
/// </summary>
public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetPreOrderEnumerator()
{
return new BinarySearchTreePreOrderEnumerator(this);
}
/// <summary>
/// Returns an enumerator that visits node in the order: left child, parent, right child
/// </summary>
public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetInOrderEnumerator()
{
return new BinarySearchTreeInOrderEnumerator(this);
}
/// <summary>
/// Returns an enumerator that visits node in the order: left child, right child, parent
/// </summary>
public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetPostOrderEnumerator()
{
return new BinarySearchTreePostOrderEnumerator(this);
}
/*********************************************************************/
/// <summary>
/// Returns an preorder-traversal enumerator for the tree values
/// </summary>
internal class BinarySearchTreePreOrderEnumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
private BSTMapNode<TKey, TValue> current;
private BinarySearchTreeMap<TKey, TValue> tree;
internal Queue<BSTMapNode<TKey, TValue>> traverseQueue;
public BinarySearchTreePreOrderEnumerator(BinarySearchTreeMap<TKey, TValue> tree)
{
this.tree = tree;
//Build queue
traverseQueue = new Queue<BSTMapNode<TKey, TValue>>();
visitNode(this.tree.Root);
}
private void visitNode(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return;
traverseQueue.Enqueue(node);
visitNode(node.LeftChild);
visitNode(node.RightChild);
}
public KeyValuePair<TKey, TValue> Current
{
get { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
current = null;
tree = null;
}
public void Reset()
{
current = null;
}
public bool MoveNext()
{
if (traverseQueue.Count > 0)
current = traverseQueue.Dequeue();
else
current = null;
return (current != null);
}
}
/// <summary>
/// Returns an inorder-traversal enumerator for the tree values
/// </summary>
internal class BinarySearchTreeInOrderEnumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
private BSTMapNode<TKey, TValue> current;
private BinarySearchTreeMap<TKey, TValue> tree;
internal Queue<BSTMapNode<TKey, TValue>> traverseQueue;
public BinarySearchTreeInOrderEnumerator(BinarySearchTreeMap<TKey, TValue> tree)
{
this.tree = tree;
//Build queue
traverseQueue = new Queue<BSTMapNode<TKey, TValue>>();
visitNode(this.tree.Root);
}
private void visitNode(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return;
visitNode(node.LeftChild);
traverseQueue.Enqueue(node);
visitNode(node.RightChild);
}
public KeyValuePair<TKey, TValue> Current
{
get { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
current = null;
tree = null;
}
public void Reset()
{
current = null;
}
public bool MoveNext()
{
if (traverseQueue.Count > 0)
current = traverseQueue.Dequeue();
else
current = null;
return (current != null);
}
}
/// <summary>
/// Returns a postorder-traversal enumerator for the tree values
/// </summary>
internal class BinarySearchTreePostOrderEnumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
private BSTMapNode<TKey, TValue> current;
private BinarySearchTreeMap<TKey, TValue> tree;
internal Queue<BSTMapNode<TKey, TValue>> traverseQueue;
public BinarySearchTreePostOrderEnumerator(BinarySearchTreeMap<TKey, TValue> tree)
{
this.tree = tree;
//Build queue
traverseQueue = new Queue<BSTMapNode<TKey, TValue>>();
visitNode(this.tree.Root);
}
private void visitNode(BSTMapNode<TKey, TValue> node)
{
if (node == null)
return;
visitNode(node.LeftChild);
visitNode(node.RightChild);
traverseQueue.Enqueue(node);
}
public KeyValuePair<TKey, TValue> Current
{
get { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); }
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
current = null;
tree = null;
}
public void Reset()
{
current = null;
}
public bool MoveNext()
{
if (traverseQueue.Count > 0)
current = traverseQueue.Dequeue();
else
current = null;
return (current != null);
}
}
}//end-of-binary-search-tree
}