-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
sortedset.cs
2469 lines (2068 loc) · 92.4 KB
/
sortedset.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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// #define USING_HASH_SET
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: SortedSet
**
** Purpose: A generic sorted set.
**
** Date: August 15, 2008
**
===========================================================*/
namespace System.Collections.Generic {
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
//
// A binary search tree is a red-black tree if it satisfies the following red-black properties:
// 1. Every node is either red or black
// 2. Every leaf (nil node) is black
// 3. If a node is red, then both its children are black
// 4. Every simple path from a node to a descendant leaf contains the same number of black nodes
//
// The basic idea of red-black tree is to represent 2-3-4 trees as standard BSTs but to add one extra bit of information
// per node to encode 3-nodes and 4-nodes.
// 4-nodes will be represented as: B
// R R
// 3 -node will be represented as: B or B
// R B B R
//
// For a detailed description of the algorithm, take a look at "Algorithms" by Robert Sedgewick.
//
internal delegate bool TreeWalkPredicate<T>(SortedSet<T>.Node node);
internal enum TreeRotation {
LeftRotation = 1,
RightRotation = 2,
RightLeftRotation = 3,
LeftRightRotation = 4,
}
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "by design name choice")]
[DebuggerTypeProxy(typeof(System.Collections.Generic.SortedSetDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
#if !FEATURE_NETCORE
[Serializable]
public class SortedSet<T> : ISet<T>, ICollection<T>, ICollection, ISerializable, IDeserializationCallback, IReadOnlyCollection<T> {
#else
public class SortedSet<T> : ISet<T>, ICollection<T>, ICollection, IReadOnlyCollection<T> {
#endif //!FEATURE_NETCORE
#region local variables/constants
Node root;
IComparer<T> comparer;
int count;
int version;
private Object _syncRoot;
private const String ComparerName = "Comparer";
private const String CountName = "Count";
private const String ItemsName = "Items";
private const String VersionName = "Version";
//needed for enumerator
private const String TreeName = "Tree";
private const String NodeValueName = "Item";
private const String EnumStartName = "EnumStarted";
private const String ReverseName = "Reverse";
private const String EnumVersionName = "EnumVersion";
#if !FEATURE_NETCORE
//needed for TreeSubset
private const String minName = "Min";
private const String maxName = "Max";
private const String lBoundActiveName = "lBoundActive";
private const String uBoundActiveName = "uBoundActive";
private SerializationInfo siInfo; //A temporary variable which we need during deserialization.
#endif
internal const int StackAllocThreshold = 100;
#endregion
#region Constructors
public SortedSet() {
this.comparer = Comparer<T>.Default;
}
public SortedSet(IComparer<T> comparer) {
if (comparer == null) {
this.comparer = Comparer<T>.Default;
} else {
this.comparer = comparer;
}
}
public SortedSet(IEnumerable<T> collection) : this(collection, Comparer<T>.Default) { }
public SortedSet(IEnumerable<T> collection, IComparer<T> comparer)
: this(comparer) {
if (collection == null) {
throw new ArgumentNullException("collection");
}
// these are explicit type checks in the mould of HashSet. It would have worked better
// with something like an ISorted<T> (we could make this work for SortedList.Keys etc)
SortedSet<T> baseSortedSet = collection as SortedSet<T>;
SortedSet<T> baseTreeSubSet = collection as TreeSubSet;
if (baseSortedSet != null && baseTreeSubSet == null && AreComparersEqual(this, baseSortedSet)) {
//breadth first traversal to recreate nodes
if (baseSortedSet.Count == 0) {
count = 0;
version = 0;
root = null;
return;
}
//pre order way to replicate nodes
Stack<Node> theirStack = new Stack<SortedSet<T>.Node>(2 * log2(baseSortedSet.Count) + 2);
Stack<Node> myStack = new Stack<SortedSet<T>.Node>(2 * log2(baseSortedSet.Count) + 2);
Node theirCurrent = baseSortedSet.root;
Node myCurrent = (theirCurrent != null ? new SortedSet<T>.Node(theirCurrent.Item, theirCurrent.IsRed) : null);
root = myCurrent;
while (theirCurrent != null) {
theirStack.Push(theirCurrent);
myStack.Push(myCurrent);
myCurrent.Left = (theirCurrent.Left != null ? new SortedSet<T>.Node(theirCurrent.Left.Item, theirCurrent.Left.IsRed) : null);
theirCurrent = theirCurrent.Left;
myCurrent = myCurrent.Left;
}
while (theirStack.Count != 0) {
theirCurrent = theirStack.Pop();
myCurrent = myStack.Pop();
Node theirRight = theirCurrent.Right;
Node myRight = null;
if (theirRight != null) {
myRight = new SortedSet<T>.Node(theirRight.Item, theirRight.IsRed);
}
myCurrent.Right = myRight;
while (theirRight != null) {
theirStack.Push(theirRight);
myStack.Push(myRight);
myRight.Left = (theirRight.Left != null ? new SortedSet<T>.Node(theirRight.Left.Item, theirRight.Left.IsRed) : null);
theirRight = theirRight.Left;
myRight = myRight.Left;
}
}
count = baseSortedSet.count;
version = 0;
} else { //As it stands, you're doing an NlogN sort of the collection
List<T> els = new List<T>(collection);
els.Sort(this.comparer);
for (int i = 1; i < els.Count; i++) {
if (comparer.Compare(els[i], els[i - 1]) == 0) {
els.RemoveAt(i);
i--;
}
}
root = ConstructRootFromSortedArray(els.ToArray(), 0, els.Count - 1, null);
count = els.Count;
version = 0;
}
}
#if !FEATURE_NETCORE
protected SortedSet(SerializationInfo info, StreamingContext context) {
siInfo = info;
}
#endif
#endregion
#region Bulk Operation Helpers
private void AddAllElements(IEnumerable<T> collection) {
foreach (T item in collection) {
if (!this.Contains(item))
Add(item);
}
}
private void RemoveAllElements(IEnumerable<T> collection) {
T min = this.Min;
T max = this.Max;
foreach (T item in collection) {
if (!(comparer.Compare(item, min) < 0 || comparer.Compare(item, max) > 0) && this.Contains(item))
this.Remove(item);
}
}
private bool ContainsAllElements(IEnumerable<T> collection) {
foreach (T item in collection) {
if (!this.Contains(item)) {
return false;
}
}
return true;
}
//
// Do a in order walk on tree and calls the delegate for each node.
// If the action delegate returns false, stop the walk.
//
// Return true if the entire tree has been walked.
// Otherwise returns false.
//
internal bool InOrderTreeWalk(TreeWalkPredicate<T> action) {
return InOrderTreeWalk(action, false);
}
// Allows for the change in traversal direction. Reverse visits nodes in descending order
internal virtual bool InOrderTreeWalk(TreeWalkPredicate<T> action, bool reverse) {
if (root == null) {
return true;
}
// The maximum height of a red-black tree is 2*lg(n+1).
// See page 264 of "Introduction to algorithms" by Thomas H. Cormen
// note: this should be logbase2, but since the stack grows itself, we
// don't want the extra cost
Stack<Node> stack = new Stack<Node>(2 * (int)(SortedSet<T>.log2(Count + 1)));
Node current = root;
while (current != null) {
stack.Push(current);
current = (reverse ? current.Right : current.Left);
}
while (stack.Count != 0) {
current = stack.Pop();
if (!action(current)) {
return false;
}
Node node = (reverse ? current.Left : current.Right);
while (node != null) {
stack.Push(node);
node = (reverse ? node.Right : node.Left);
}
}
return true;
}
//
// Do a left to right breadth first walk on tree and
// calls the delegate for each node.
// If the action delegate returns false, stop the walk.
//
// Return true if the entire tree has been walked.
// Otherwise returns false.
//
internal virtual bool BreadthFirstTreeWalk(TreeWalkPredicate<T> action) {
if (root == null) {
return true;
}
List<Node> processQueue = new List<Node>();
processQueue.Add(root);
Node current;
while (processQueue.Count != 0) {
current = processQueue[0];
processQueue.RemoveAt(0);
if (!action(current)) {
return false;
}
if (current.Left != null) {
processQueue.Add(current.Left);
}
if (current.Right != null) {
processQueue.Add(current.Right);
}
}
return true;
}
#endregion
#region Properties
public int Count {
get {
VersionCheck();
return count;
}
}
public IComparer<T> Comparer {
get {
return comparer;
}
}
bool ICollection<T>.IsReadOnly {
get {
return false;
}
}
bool ICollection.IsSynchronized {
get {
return false;
}
}
object ICollection.SyncRoot {
get {
if (_syncRoot == null) {
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
#endregion
#region Subclass helpers
//virtual function for subclass that needs to update count
internal virtual void VersionCheck() { }
//virtual function for subclass that needs to do range checks
internal virtual bool IsWithinRange(T item) {
return true;
}
#endregion
#region ICollection<T> Members
/// <summary>
/// Add the value ITEM to the tree, returns true if added, false if duplicate
/// </summary>
/// <param name="item">item to be added</param>
public bool Add(T item) {
return AddIfNotPresent(item);
}
void ICollection<T>.Add(T item) {
AddIfNotPresent(item);
}
/// <summary>
/// Adds ITEM to the tree if not already present. Returns TRUE if value was successfully added
/// or FALSE if it is a duplicate
/// </summary>
internal virtual bool AddIfNotPresent(T item) {
if (root == null) { // empty tree
root = new Node(item, false);
count = 1;
version++;
return true;
}
//
// Search for a node at bottom to insert the new node.
// If we can guanratee the node we found is not a 4-node, it would be easy to do insertion.
// We split 4-nodes along the search path.
//
Node current = root;
Node parent = null;
Node grandParent = null;
Node greatGrandParent = null;
//even if we don't actually add to the set, we may be altering its structure (by doing rotations
//and such). so update version to disable any enumerators/subsets working on it
version++;
int order = 0;
while (current != null) {
order = comparer.Compare(item, current.Item);
if (order == 0) {
// We could have changed root node to red during the search process.
// We need to set it to black before we return.
root.IsRed = false;
return false;
}
// split a 4-node into two 2-nodes
if (Is4Node(current)) {
Split4Node(current);
// We could have introduced two consecutive red nodes after split. Fix that by rotation.
if (IsRed(parent)) {
InsertionBalance(current, ref parent, grandParent, greatGrandParent);
}
}
greatGrandParent = grandParent;
grandParent = parent;
parent = current;
current = (order < 0) ? current.Left : current.Right;
}
Debug.Assert(parent != null, "Parent node cannot be null here!");
// ready to insert the new node
Node node = new Node(item);
if (order > 0) {
parent.Right = node;
} else {
parent.Left = node;
}
// the new node will be red, so we will need to adjust the colors if parent node is also red
if (parent.IsRed) {
InsertionBalance(node, ref parent, grandParent, greatGrandParent);
}
// Root node is always black
root.IsRed = false;
++count;
return true;
}
/// <summary>
/// Remove the T ITEM from this SortedSet. Returns true if successfully removed.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Remove(T item) {
return this.DoRemove(item); // hack so it can be made non-virtual
}
internal virtual bool DoRemove(T item) {
if (root == null) {
return false;
}
// Search for a node and then find its succesor.
// Then copy the item from the succesor to the matching node and delete the successor.
// If a node doesn't have a successor, we can replace it with its left child (if not empty.)
// or delete the matching node.
//
// In top-down implementation, it is important to make sure the node to be deleted is not a 2-node.
// Following code will make sure the node on the path is not a 2 Node.
//even if we don't actually remove from the set, we may be altering its structure (by doing rotations
//and such). so update version to disable any enumerators/subsets working on it
version++;
Node current = root;
Node parent = null;
Node grandParent = null;
Node match = null;
Node parentOfMatch = null;
bool foundMatch = false;
while (current != null) {
if (Is2Node(current)) { // fix up 2-Node
if (parent == null) { // current is root. Mark it as red
current.IsRed = true;
} else {
Node sibling = GetSibling(current, parent);
if (sibling.IsRed) {
// If parent is a 3-node, flip the orientation of the red link.
// We can acheive this by a single rotation
// This case is converted to one of other cased below.
Debug.Assert(!parent.IsRed, "parent must be a black node!");
if (parent.Right == sibling) {
RotateLeft(parent);
} else {
RotateRight(parent);
}
parent.IsRed = true;
sibling.IsRed = false; // parent's color
// sibling becomes child of grandParent or root after rotation. Update link from grandParent or root
ReplaceChildOfNodeOrRoot(grandParent, parent, sibling);
// sibling will become grandParent of current node
grandParent = sibling;
if (parent == match) {
parentOfMatch = sibling;
}
// update sibling, this is necessary for following processing
sibling = (parent.Left == current) ? parent.Right : parent.Left;
}
Debug.Assert(sibling != null || sibling.IsRed == false, "sibling must not be null and it must be black!");
if (Is2Node(sibling)) {
Merge2Nodes(parent, current, sibling);
} else {
// current is a 2-node and sibling is either a 3-node or a 4-node.
// We can change the color of current to red by some rotation.
TreeRotation rotation = RotationNeeded(parent, current, sibling);
Node newGrandParent = null;
switch (rotation) {
case TreeRotation.RightRotation:
Debug.Assert(parent.Left == sibling, "sibling must be left child of parent!");
Debug.Assert(sibling.Left.IsRed, "Left child of sibling must be red!");
sibling.Left.IsRed = false;
newGrandParent = RotateRight(parent);
break;
case TreeRotation.LeftRotation:
Debug.Assert(parent.Right == sibling, "sibling must be left child of parent!");
Debug.Assert(sibling.Right.IsRed, "Right child of sibling must be red!");
sibling.Right.IsRed = false;
newGrandParent = RotateLeft(parent);
break;
case TreeRotation.RightLeftRotation:
Debug.Assert(parent.Right == sibling, "sibling must be left child of parent!");
Debug.Assert(sibling.Left.IsRed, "Left child of sibling must be red!");
newGrandParent = RotateRightLeft(parent);
break;
case TreeRotation.LeftRightRotation:
Debug.Assert(parent.Left == sibling, "sibling must be left child of parent!");
Debug.Assert(sibling.Right.IsRed, "Right child of sibling must be red!");
newGrandParent = RotateLeftRight(parent);
break;
}
newGrandParent.IsRed = parent.IsRed;
parent.IsRed = false;
current.IsRed = true;
ReplaceChildOfNodeOrRoot(grandParent, parent, newGrandParent);
if (parent == match) {
parentOfMatch = newGrandParent;
}
grandParent = newGrandParent;
}
}
}
// we don't need to compare any more once we found the match
int order = foundMatch ? -1 : comparer.Compare(item, current.Item);
if (order == 0) {
// save the matching node
foundMatch = true;
match = current;
parentOfMatch = parent;
}
grandParent = parent;
parent = current;
if (order < 0) {
current = current.Left;
} else {
current = current.Right; // continue the search in right sub tree after we find a match
}
}
// move successor to the matching node position and replace links
if (match != null) {
ReplaceNode(match, parentOfMatch, parent, grandParent);
--count;
}
if (root != null) {
root.IsRed = false;
}
return foundMatch;
}
public virtual void Clear() {
root = null;
count = 0;
++version;
}
public virtual bool Contains(T item) {
return FindNode(item) != null;
}
public void CopyTo(T[] array) { CopyTo(array, 0, Count); }
public void CopyTo(T[] array, int index) { CopyTo(array, index, Count); }
public void CopyTo(T[] array, int index, int count) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
}
// will array, starting at arrayIndex, be able to hold elements? Note: not
// checking arrayIndex >= array.Length (consistency with list of allowing
// count of 0; subsequent check takes care of the rest)
if (index > array.Length || count > array.Length - index) {
throw new ArgumentException(SR.GetString(SR.Arg_ArrayPlusOffTooSmall));
}
//upper bound
count += index;
InOrderTreeWalk(delegate(Node node) {
if (index >= count) {
return false;
} else {
array[index++] = node.Item;
return true;
}
});
}
void ICollection.CopyTo(Array array, int index) {
if (array == null) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (array.Rank != 1) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
if (index < 0) {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
T[] tarray = array as T[];
if (tarray != null) {
CopyTo(tarray, index);
} else {
object[] objects = array as object[];
if (objects == null) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
try {
InOrderTreeWalk(delegate(Node node) { objects[index++] = node.Item; return true; });
} catch (ArrayTypeMismatchException) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
}
}
#endregion
#region IEnumerable<T> members
public Enumerator GetEnumerator() {
return new Enumerator(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator() {
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator() {
return new Enumerator(this);
}
#endregion
#region Tree Specific Operations
private static Node GetSibling(Node node, Node parent) {
if (parent.Left == node) {
return parent.Right;
}
return parent.Left;
}
// After calling InsertionBalance, we need to make sure current and parent up-to-date.
// It doesn't matter if we keep grandParent and greatGrantParent up-to-date
// because we won't need to split again in the next node.
// By the time we need to split again, everything will be correctly set.
//
private void InsertionBalance(Node current, ref Node parent, Node grandParent, Node greatGrandParent) {
Debug.Assert(grandParent != null, "Grand parent cannot be null here!");
bool parentIsOnRight = (grandParent.Right == parent);
bool currentIsOnRight = (parent.Right == current);
Node newChildOfGreatGrandParent;
if (parentIsOnRight == currentIsOnRight) { // same orientation, single rotation
newChildOfGreatGrandParent = currentIsOnRight ? RotateLeft(grandParent) : RotateRight(grandParent);
} else { // different orientaton, double rotation
newChildOfGreatGrandParent = currentIsOnRight ? RotateLeftRight(grandParent) : RotateRightLeft(grandParent);
// current node now becomes the child of greatgrandparent
parent = greatGrandParent;
}
// grand parent will become a child of either parent of current.
grandParent.IsRed = true;
newChildOfGreatGrandParent.IsRed = false;
ReplaceChildOfNodeOrRoot(greatGrandParent, grandParent, newChildOfGreatGrandParent);
}
private static bool Is2Node(Node node) {
Debug.Assert(node != null, "node cannot be null!");
return IsBlack(node) && IsNullOrBlack(node.Left) && IsNullOrBlack(node.Right);
}
private static bool Is4Node(Node node) {
return IsRed(node.Left) && IsRed(node.Right);
}
private static bool IsBlack(Node node) {
return (node != null && !node.IsRed);
}
private static bool IsNullOrBlack(Node node) {
return (node == null || !node.IsRed);
}
private static bool IsRed(Node node) {
return (node != null && node.IsRed);
}
private static void Merge2Nodes(Node parent, Node child1, Node child2) {
Debug.Assert(IsRed(parent), "parent must be be red");
// combing two 2-nodes into a 4-node
parent.IsRed = false;
child1.IsRed = true;
child2.IsRed = true;
}
// Replace the child of a parent node.
// If the parent node is null, replace the root.
private void ReplaceChildOfNodeOrRoot(Node parent, Node child, Node newChild) {
if (parent != null) {
if (parent.Left == child) {
parent.Left = newChild;
} else {
parent.Right = newChild;
}
} else {
root = newChild;
}
}
// Replace the matching node with its succesor.
private void ReplaceNode(Node match, Node parentOfMatch, Node succesor, Node parentOfSuccesor) {
if (succesor == match) { // this node has no successor, should only happen if right child of matching node is null.
Debug.Assert(match.Right == null, "Right child must be null!");
succesor = match.Left;
} else {
Debug.Assert(parentOfSuccesor != null, "parent of successor cannot be null!");
Debug.Assert(succesor.Left == null, "Left child of succesor must be null!");
Debug.Assert((succesor.Right == null && succesor.IsRed) || (succesor.Right.IsRed && !succesor.IsRed), "Succesor must be in valid state");
if (succesor.Right != null) {
succesor.Right.IsRed = false;
}
if (parentOfSuccesor != match) { // detach succesor from its parent and set its right child
parentOfSuccesor.Left = succesor.Right;
succesor.Right = match.Right;
}
succesor.Left = match.Left;
}
if (succesor != null) {
succesor.IsRed = match.IsRed;
}
ReplaceChildOfNodeOrRoot(parentOfMatch, match, succesor);
}
internal virtual Node FindNode(T item) {
Node current = root;
while (current != null) {
int order = comparer.Compare(item, current.Item);
if (order == 0) {
return current;
} else {
current = (order < 0) ? current.Left : current.Right;
}
}
return null;
}
//used for bithelpers. Note that this implementation is completely different
//from the Subset's. The two should not be mixed. This indexes as if the tree were an array.
//http://en.wikipedia.org/wiki/Binary_Tree#Methods_for_storing_binary_trees
internal virtual int InternalIndexOf(T item) {
Node current = root;
int count = 0;
while (current != null) {
int order = comparer.Compare(item, current.Item);
if (order == 0) {
return count;
} else {
current = (order < 0) ? current.Left : current.Right;
count = (order < 0) ? (2 * count + 1) : (2 * count + 2);
}
}
return -1;
}
internal Node FindRange(T from, T to) {
return FindRange(from, to, true, true);
}
internal Node FindRange(T from, T to, bool lowerBoundActive, bool upperBoundActive) {
Node current = root;
while (current != null) {
if (lowerBoundActive && comparer.Compare(from, current.Item) > 0) {
current = current.Right;
} else {
if (upperBoundActive && comparer.Compare(to, current.Item) < 0) {
current = current.Left;
} else {
return current;
}
}
}
return null;
}
internal void UpdateVersion() {
++version;
}
private static Node RotateLeft(Node node) {
Node x = node.Right;
node.Right = x.Left;
x.Left = node;
return x;
}
private static Node RotateLeftRight(Node node) {
Node child = node.Left;
Node grandChild = child.Right;
node.Left = grandChild.Right;
grandChild.Right = node;
child.Right = grandChild.Left;
grandChild.Left = child;
return grandChild;
}
private static Node RotateRight(Node node) {
Node x = node.Left;
node.Left = x.Right;
x.Right = node;
return x;
}
private static Node RotateRightLeft(Node node) {
Node child = node.Right;
Node grandChild = child.Left;
node.Right = grandChild.Left;
grandChild.Left = node;
child.Left = grandChild.Right;
grandChild.Right = child;
return grandChild;
}
/// <summary>
/// Testing counter that can track rotations
/// </summary>
private static TreeRotation RotationNeeded(Node parent, Node current, Node sibling) {
Debug.Assert(IsRed(sibling.Left) || IsRed(sibling.Right), "sibling must have at least one red child");
if (IsRed(sibling.Left)) {
if (parent.Left == current) {
return TreeRotation.RightLeftRotation;
}
return TreeRotation.RightRotation;
} else {
if (parent.Left == current) {
return TreeRotation.LeftRotation;
}
return TreeRotation.LeftRightRotation;
}
}
/// <summary>
/// Used for deep equality of SortedSet testing
/// </summary>
/// <returns></returns>
public static IEqualityComparer<SortedSet<T>> CreateSetComparer() {
return new SortedSetEqualityComparer<T>();
}
/// <summary>
/// Create a new set comparer for this set, where this set's members' equality is defined by the
/// memberEqualityComparer. Note that this equality comparer's definition of equality must be the
/// same as this set's Comparer's definition of equality
/// </summary>
public static IEqualityComparer<SortedSet<T>> CreateSetComparer(IEqualityComparer<T> memberEqualityComparer) {
return new SortedSetEqualityComparer<T>(memberEqualityComparer);
}
/// <summary>
/// Decides whether these sets are the same, given the comparer. If the EC's are the same, we can
/// just use SetEquals, but if they aren't then we have to manually check with the given comparer
/// </summary>
internal static bool SortedSetEquals(SortedSet<T> set1, SortedSet<T> set2, IComparer<T> comparer) {
// handle null cases first
if (set1 == null) {
return (set2 == null);
} else if (set2 == null) {
// set1 != null
return false;
}
if (AreComparersEqual(set1, set2)) {
if (set1.Count != set2.Count)
return false;
return set1.SetEquals(set2);
} else {
bool found = false;
foreach (T item1 in set1) {
found = false;
foreach (T item2 in set2) {
if (comparer.Compare(item1, item2) == 0) {
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
}
//This is a little frustrating because we can't support more sorted structures
private static bool AreComparersEqual(SortedSet<T> set1, SortedSet<T> set2) {
return set1.Comparer.Equals(set2.Comparer);
}
private static void Split4Node(Node node) {
node.IsRed = true;
node.Left.IsRed = false;
node.Right.IsRed = false;
}
/// <summary>
/// Copies this to an array. Used for DebugView
/// </summary>
/// <returns></returns>
internal T[] ToArray() {
T[] newArray = new T[Count];
CopyTo(newArray);
return newArray;
}
#endregion
#region ISet Members
/// <summary>
/// Transform this set into its union with the IEnumerable OTHER
///Attempts to insert each element and rejects it if it exists.
/// NOTE: The caller object is important as UnionWith uses the Comparator
///associated with THIS to check equality
/// Throws ArgumentNullException if OTHER is null
/// </summary>
/// <param name="other"></param>
public void UnionWith(IEnumerable<T> other) {
if (other == null) {
throw new ArgumentNullException("other");
}
SortedSet<T> s = other as SortedSet<T>;
TreeSubSet t = this as TreeSubSet;
if (t != null)
VersionCheck();
if (s != null && t == null && this.count == 0) {
SortedSet<T> dummy = new SortedSet<T>(s, this.comparer);
this.root = dummy.root;
this.count = dummy.count;
this.version++;