forked from google/quiver-dart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
treeset.dart
1049 lines (943 loc) · 28.5 KB
/
treeset.dart
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
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:collection';
int _defaultCompare(a, b) {
return a.compareTo(b);
}
/// A [Set] of items stored in a binary tree according to [comparator].
/// Supports bidirectional iteration.
abstract class TreeSet<V> extends IterableBase<V> implements Set<V> {
/// Create a new [TreeSet] with an ordering defined by [comparator] or the
/// default `(a, b) => a.compareTo(b)`.
factory TreeSet({Comparator<V> comparator = _defaultCompare}) {
return AvlTreeSet(comparator: comparator);
}
TreeSet._(this.comparator);
final Comparator<V> comparator;
@override
int get length;
@override
bool get isEmpty => length == 0;
@override
bool get isNotEmpty => length != 0;
/// Returns a [TreeIterator] that iterates over this tree.
@override
TreeIterator<V> get iterator;
/// Returns a [TreeIterator] that iterates over this tree, in
/// reverse.
TreeIterator<V> get reverseIterator;
/// Returns a [TreeIterator] that starts at [anchor]. By default,
/// the iterator includes the anchor with the first movement; set [inclusive]
/// to false if you want to exclude the anchor. Set [reversed] to true to
/// change the direction of of moveNext and movePrevious.
///
/// Note: This iterator allows you to walk the entire set. It does not
/// present a subview.
TreeIterator<V> fromIterator(V anchor,
{bool reversed = false, bool inclusive = true});
/// Search the tree for the matching [object] or the [nearestOption]
/// if missing. See [TreeSearch].
V nearest(V object, {TreeSearch nearestOption = TreeSearch.NEAREST});
@override
Set<T> cast<T>();
// TODO(codefu): toString or not toString, that is the question.
}
/// Controls the results for [TreeSet.searchNearest]()
enum TreeSearch {
/// If result not found, always chose the smaller element
// ignore: constant_identifier_names
LESS_THAN,
/// If result not found, chose the nearest based on comparison
// ignore: constant_identifier_names
NEAREST,
/// If result not found, always chose the greater element
// ignore: constant_identifier_names
GREATER_THAN
}
/// A node in the [TreeSet].
abstract class _TreeNode<V> {
/// TreeNodes are always allocated as leafs.
_TreeNode({required this.object});
_TreeNode<V> get left;
bool get hasLeft;
_TreeNode<V> get right;
bool get hasRight;
// TODO(codefu): Remove need for [parent]; this is just an implementation
// note.
_TreeNode<V> get parent;
bool get hasParent;
V object;
/// Return the minimum node for the subtree
_TreeNode<V> get minimumNode {
var node = this;
while (node.hasLeft) {
node = node.left;
}
return node;
}
/// Return the maximum node for the subtree
_TreeNode<V> get maximumNode {
var node = this;
while (node.hasRight) {
node = node.right;
}
return node;
}
/// Return the next greatest element (or null)
_TreeNode<V>? get successor {
var node = this;
if (node.hasRight) {
return node.right.minimumNode;
}
while (
node.hasParent && node.parent.hasRight && node == node.parent.right) {
node = node.parent;
}
return node.hasParent ? node.parent : null;
}
/// Return the next smaller element (or null)
_TreeNode<V>? get predecessor {
var node = this;
if (node.hasLeft) {
return node.left.maximumNode;
}
while (node.hasParent && node.parent.hasLeft && node.parent.left == node) {
node = node.parent;
}
return node.hasParent ? node.parent : null;
}
}
/// AVL implementation of a self-balancing binary tree. Optimized for lookup
/// operations.
///
/// Notes: Adapted from "Introduction to Algorithms", second edition,
/// by Thomas H. Cormen, Charles E. Leiserson,
/// Ronald L. Rivest, Clifford Stein.
/// chapter 13.2
class AvlTreeSet<V> extends TreeSet<V> {
AvlTreeSet({Comparator<V> comparator = _defaultCompare})
: super._(comparator);
int _length = 0;
AvlNode<V>? _root;
// Modification count to the tree, monotonically increasing
int _modCount = 0;
@override
int get length => _length;
/// Add the element to the tree.
@override
bool add(V element) {
if (_root == null) {
AvlNode<V> node = AvlNode<V>(object: element);
_root = node;
++_length;
++_modCount;
return true;
}
AvlNode<V> x = _root!;
while (true) {
int compare = comparator(element, x.object);
if (compare == 0) {
return false;
} else if (compare < 0) {
if (!x.hasLeft) {
AvlNode<V> node = AvlNode<V>(object: element).._parent = x;
x
.._left = node
.._balanceFactor -= 1;
break;
}
x = x.left;
} else {
if (!x.hasRight) {
AvlNode<V> node = AvlNode<V>(object: element).._parent = x;
x
.._right = node
.._balanceFactor += 1;
break;
}
x = x.right;
}
}
++_modCount;
// AVL balancing act (for height balanced trees)
// Now that we've inserted, we've unbalanced some trees, we need
// to follow the tree back up to the _root double checking that the tree
// is still balanced and _maybe_ perform a single or double rotation.
// Note: Left additions == -1, Right additions == +1
// Balanced Node = { -1, 0, 1 }, out of balance = { -2, 2 }
// Single rotation when Parent & Child share signed balance,
// Double rotation when sign differs!
AvlNode<V> node = x;
while (node._balanceFactor != 0 && node.hasParent) {
// Find out which side of the parent we're on
if (node.parent._left == node) {
node.parent._balanceFactor -= 1;
} else {
node.parent._balanceFactor += 1;
}
node = node.parent;
if (node._balanceFactor == 2) {
// Heavy on the right side - Test for which rotation to perform
if (node.right._balanceFactor == 1) {
// Single (left) rotation; this will balance everything to zero
_rotateLeft(node);
node._balanceFactor = node.parent._balanceFactor = 0;
node = node.parent;
} else {
// Double (Right/Left) rotation
// node will now be old node.right.left
_rotateRightLeft(node);
node = node.parent; // Update to new parent (old grandchild)
if (node._balanceFactor == 1) {
node.right._balanceFactor = 0;
node.left._balanceFactor = -1;
} else if (node._balanceFactor == 0) {
node.right._balanceFactor = 0;
node.left._balanceFactor = 0;
} else {
node.right._balanceFactor = 1;
node.left._balanceFactor = 0;
}
node._balanceFactor = 0;
}
break; // out of loop, we're balanced
} else if (node._balanceFactor == -2) {
// Heavy on the left side - Test for which rotation to perform
if (node.left._balanceFactor == -1) {
_rotateRight(node);
node._balanceFactor = node.parent._balanceFactor = 0;
node = node.parent;
} else {
// Double (Left/Right) rotation
// node will now be old node.left.right
_rotateLeftRight(node);
node = node.parent;
if (node._balanceFactor == -1) {
node.right._balanceFactor = 1;
node.left._balanceFactor = 0;
} else if (node._balanceFactor == 0) {
node.right._balanceFactor = 0;
node.left._balanceFactor = 0;
} else {
node.right._balanceFactor = 0;
node.left._balanceFactor = -1;
}
node._balanceFactor = 0;
}
break; // out of loop, we're balanced
}
} // end of while (balancing)
_length++;
return true;
}
/// Test to see if an element is stored in the tree
AvlNode<V>? _getNode(V element) {
AvlNode<V>? x = _root;
while (x != null) {
int compare = comparator(element, x.object);
if (compare == 0) {
// This only means our node matches; we need to search for the exact
// element. We could have been glutons and used a hashmap to back.
return x;
} else if (compare < 0) {
x = x._left;
} else {
x = x._right;
}
}
return null;
}
/// This function will right rotate/pivot N with its left child, placing
/// it on the right of its left child.
///
/// N Y
/// / \ / \
/// Y A Z N
/// / \ ==> / \ / \
/// Z B D CB A
/// / \
/// D C
///
/// Assertion: must have a left element
void _rotateRight(AvlNode<V> node) {
AvlNode<V>? y = node.left;
// turn Y's right subtree(B) into N's left subtree.
node._left = y._right;
if (node.hasLeft) {
node.left._parent = node;
}
y._parent = node._parent;
if (y.hasParent) {
if (node.parent._left == node) {
node.parent._left = y;
} else {
node.parent._right = y;
}
} else {
_root = y;
}
y._right = node;
node._parent = y;
}
/// This function will left rotate/pivot N with its right child, placing
/// it on the left of its right child.
///
/// N Y
/// / \ / \
/// A Y N Z
/// / \ ==> / \ / \
/// B Z A BC D
/// / \
/// C D
///
/// Assertion: must have a right element
void _rotateLeft(AvlNode<V> node) {
AvlNode<V>? y = node.right;
// turn Y's left subtree(B) into N's right subtree.
node._right = y._left;
if (node.hasRight) {
node.right._parent = node;
}
y._parent = node._parent;
if (y.hasParent) {
if (node.parent._left == node) {
y.parent._left = y;
} else {
y.parent._right = y;
}
} else {
_root = y;
}
y._left = node;
node._parent = y;
}
/// This function will double rotate node with right/left operations.
/// node is S.
///
/// S G
/// / \ / \
/// A C S C
/// / \ ==> / \ / \
/// G B A DC B
/// / \
/// D C
void _rotateRightLeft(AvlNode<V> node) {
_rotateRight(node.right);
_rotateLeft(node);
}
/// This function will double rotate node with left/right operations.
/// node is S.
///
/// S G
/// / \ / \
/// C A C S
/// / \ ==> / \ / \
/// B G B CD A
/// / \
/// C D
void _rotateLeftRight(AvlNode<V> node) {
_rotateLeft(node.left);
_rotateRight(node);
}
@override
bool addAll(Iterable<V> items) {
bool modified = false;
for (final item in items) {
if (add(item)) {
modified = true;
}
}
return modified;
}
@override
AvlTreeSet<T> cast<T>() {
// TODO(codefu): Dart 2.0 requires this method to be implemented.
throw UnimplementedError('cast');
}
@override
void clear() {
_length = 0;
_root = null;
++_modCount;
}
@override
bool containsAll(Iterable<Object?> items) {
for (final item in items) {
if (!contains(item)) return false;
}
return true;
}
@override
bool remove(Object? item) {
if (item is! V) return false;
AvlNode<V>? x = _getNode(item);
if (x != null) {
_removeNode(x);
return true;
}
return false;
}
void _removeNode(AvlNode<V> node) {
AvlNode<V>? y;
AvlNode<V>? w;
++_modCount;
--_length;
// note: if you read wikipedia, it states remove the node if its a leaf,
// otherwise, replace it with its predecessor or successor. We're not.
if (!node.hasRight || !node.right.hasLeft) {
// simple solutions
if (node.hasRight) {
y = node.right;
y._parent = node._parent;
y._balanceFactor = node._balanceFactor - 1;
y._left = node._left;
if (y.hasLeft) {
y.left._parent = y;
}
} else if (node.hasLeft) {
y = node.left;
y._parent = node._parent;
y._balanceFactor = node._balanceFactor + 1;
} else {
y = null;
}
if (_root == node) {
_root = y;
} else if (node.parent._left == node) {
node.parent._left = y;
if (y == null) {
// account for leaf deletions changing the balance
node.parent._balanceFactor += 1;
y = node.parent; // start searching from here;
}
} else {
node.parent._right = y;
if (y == null) {
node.parent._balanceFactor -= 1;
y = node.parent;
}
}
w = y;
} else {
// This node is not a leaf; we should find the successor node, swap
//it with this* and then update the balance factors.
y = node.successor as AvlNode<V>;
y._left = node._left;
if (y.hasLeft) {
y.left._parent = y;
}
w = y.parent;
w._left = y._right;
if (w.hasLeft) {
w.left._parent = w;
}
// known: we're removing from the left
w._balanceFactor += 1;
// known due to test for n->r->l above
y._right = node._right;
y.right._parent = y;
y._balanceFactor = node._balanceFactor;
y._parent = node._parent;
if (_root == node) {
_root = y;
} else if (node.parent._left == node) {
node.parent._left = y;
} else {
node.parent._right = y;
}
}
// Safe to kill node now; its free to go.
node._balanceFactor = 0;
node._left = node._right = node._parent = null;
// Re-balance to the top, ending early if OK
_rebalance(w);
}
void _rebalance(AvlNode<V>? node) {
while (node != null) {
if (node._balanceFactor == -1 || node._balanceFactor == 1) {
// The height of node hasn't changed; done!
break;
}
if (node._balanceFactor == 2) {
// Heavy on the right side; figure out which rotation to perform
if (node.right._balanceFactor == -1) {
_rotateRightLeft(node);
node = node.parent; // old grand-child!
if (node._balanceFactor == 1) {
node.right._balanceFactor = 0;
node.left._balanceFactor = -1;
} else if (node._balanceFactor == 0) {
node.right._balanceFactor = 0;
node.left._balanceFactor = 0;
} else {
node.right._balanceFactor = 1;
node.left._balanceFactor = 0;
}
node._balanceFactor = 0;
} else {
// single left-rotation
_rotateLeft(node);
if (node.parent._balanceFactor == 0) {
node.parent._balanceFactor = -1;
node._balanceFactor = 1;
break;
} else {
node.parent._balanceFactor = 0;
node._balanceFactor = 0;
node = node.parent;
continue;
}
}
} else if (node._balanceFactor == -2) {
// Heavy on the left
if (node.left._balanceFactor == 1) {
_rotateLeftRight(node);
node = node.parent; // old grand-child!
if (node._balanceFactor == -1) {
node.right._balanceFactor = 1;
node.left._balanceFactor = 0;
} else if (node._balanceFactor == 0) {
node.right._balanceFactor = 0;
node.left._balanceFactor = 0;
} else {
node.right._balanceFactor = 0;
node.left._balanceFactor = -1;
}
node._balanceFactor = 0;
} else {
_rotateRight(node);
if (node.parent._balanceFactor == 0) {
node.parent._balanceFactor = 1;
node._balanceFactor = -1;
break;
} else {
node.parent._balanceFactor = 0;
node._balanceFactor = 0;
node = node.parent;
continue;
}
}
}
// continue up the tree for testing
if (node.hasParent) {
// The concept of balance here is reverse from addition; since
// we are taking away weight from one side or the other (thus
// the balance changes in favor of the other side)
if (node.parent.hasLeft && node.parent.left == node) {
node.parent._balanceFactor += 1;
} else {
node.parent._balanceFactor -= 1;
}
}
node = node.hasParent ? node.parent : null;
}
}
/// See [Set.removeAll]
@override
void removeAll(Iterable items) {
items.forEach(remove);
}
/// See [Set.retainAll]
@override
void retainAll(Iterable<Object?> elements) {
List<V> chosen = <V>[];
for (final target in elements) {
if (target is V && contains(target)) {
chosen.add(target);
}
}
clear();
addAll(chosen);
}
/// See [Set.retainWhere]
@override
void retainWhere(bool Function(V element) test) {
List<V> chosen = [];
for (final target in this) {
if (test(target)) {
chosen.add(target);
}
}
clear();
addAll(chosen);
}
/// See [Set.removeWhere]
@override
void removeWhere(bool Function(V element) test) {
List<V> damned = [];
for (final target in this) {
if (test(target)) {
damned.add(target);
}
}
removeAll(damned);
}
/// See [IterableBase.first]
@override
V get first {
_TreeNode<V>? min = _root?.minimumNode;
if (min != null) {
return min.object;
}
throw StateError('No first element');
}
/// See [IterableBase.last]
@override
V get last {
_TreeNode<V>? max = _root?.maximumNode;
if (max != null) {
return max.object;
}
throw StateError('No last element');
}
/// See [Set.lookup]
@override
V? lookup(Object? element) {
if (element is! V || _root == null) return null;
AvlNode<V>? x = _root;
int compare = 0;
while (x != null) {
compare = comparator(element, x.object);
if (compare == 0) {
return x.object;
} else if (compare < 0) {
x = x._left;
} else {
x = x._right;
}
}
return null;
}
@override
V nearest(V object, {TreeSearch nearestOption = TreeSearch.NEAREST}) {
AvlNode<V>? found = _searchNearest(object, option: nearestOption);
if (found != null) {
return found.object;
}
throw StateError('No nearest element');
}
/// Search the tree for the matching element, or the 'nearest' node.
/// NOTE: [BinaryTree.comparator] needs to have finer granularity than -1,0,1
/// in order for this to return something that's meaningful.
AvlNode<V>? _searchNearest(V? element,
{TreeSearch option = TreeSearch.NEAREST}) {
if (element == null || _root == null) {
return null;
}
AvlNode<V>? x = _root;
late AvlNode<V> previous;
int compare = 0;
while (x != null) {
previous = x;
compare = comparator(element, x.object);
if (compare == 0) {
return x;
} else if (compare < 0) {
x = x._left;
} else {
x = x._right;
}
}
if (option == TreeSearch.GREATER_THAN) {
return (compare < 0 ? previous : previous.successor) as AvlNode<V>?;
} else if (option == TreeSearch.LESS_THAN) {
return (compare < 0 ? previous.predecessor : previous) as AvlNode<V>?;
}
// Default: nearest absolute value
// Fell off the tree looking for the exact match; now we need
// to find the nearest element.
x = (compare < 0 ? previous.predecessor : previous.successor)
as AvlNode<V>?;
if (x == null) {
return previous;
}
int otherCompare = comparator(element, x.object);
if (compare < 0) {
return compare.abs() < otherCompare ? previous : x;
}
return otherCompare.abs() < compare ? x : previous;
}
//
// [IterableBase]<V> Methods
//
/// See [IterableBase.iterator]
@override
TreeIterator<V> get iterator => TreeIterator._(this);
/// See [TreeSet.reverseIterator]
@override
TreeIterator<V> get reverseIterator => TreeIterator._(this, reversed: true);
/// See [TreeSet.fromIterator]
@override
TreeIterator<V> fromIterator(V anchor,
{bool reversed = false, bool inclusive = true}) =>
TreeIterator<V>._(this,
anchorObject: anchor, reversed: reversed, inclusive: inclusive);
/// See [IterableBase.contains]
@override
bool contains(Object? object) {
if (object is! V) {
return false;
}
return _getNode(object) != null;
}
//
// [Set] methods
//
/// See [Set.intersection]
@override
Set<V> intersection(Set<Object?> other) {
TreeSet<V> set = TreeSet(comparator: comparator);
// Optimized for sorted sets
if (other is TreeSet<V>) {
var i1 = iterator;
var i2 = other.iterator;
var hasMore1 = i1.moveNext();
var hasMore2 = i2.moveNext();
while (hasMore1 && hasMore2) {
var c = comparator(i1.current, i2.current);
if (c == 0) {
set.add(i1.current);
hasMore1 = i1.moveNext();
hasMore2 = i2.moveNext();
} else if (c < 0) {
hasMore1 = i1.moveNext();
} else {
hasMore2 = i2.moveNext();
}
}
return set;
}
// Non-optimized version.
for (final target in this) {
if (other.contains(target)) {
set.add(target);
}
}
return set;
}
/// See [Set.union]
@override
Set<V> union(Set<V> other) {
TreeSet<V> set = TreeSet(comparator: comparator);
if (other is TreeSet) {
Iterator<V> i1 = iterator;
var i2 = other.iterator;
var hasMore1 = i1.moveNext();
var hasMore2 = i2.moveNext();
while (hasMore1 && hasMore2) {
var c = comparator(i1.current, i2.current);
if (c == 0) {
set.add(i1.current);
hasMore1 = i1.moveNext();
hasMore2 = i2.moveNext();
} else if (c < 0) {
set.add(i1.current);
hasMore1 = i1.moveNext();
} else {
set.add(i2.current);
hasMore2 = i2.moveNext();
}
}
if (hasMore1 || hasMore2) {
i1 = hasMore1 ? i1 : i2;
do {
set.add(i1.current);
} while (i1.moveNext());
}
return set;
}
// Non-optimized version.
return set
..addAll(this)
..addAll(other);
}
/// See [Set.difference]
@override
Set<V> difference(Set<Object?> other) {
TreeSet<V> set = TreeSet(comparator: comparator);
if (other is TreeSet) {
var i1 = iterator;
var i2 = other.iterator;
var hasMore1 = i1.moveNext();
var hasMore2 = i2.moveNext();
while (hasMore1 && hasMore2) {
var c = comparator(i1.current, i2.current);
if (c == 0) {
hasMore1 = i1.moveNext();
hasMore2 = i2.moveNext();
} else if (c < 0) {
set.add(i1.current);
hasMore1 = i1.moveNext();
} else {
hasMore2 = i2.moveNext();
}
}
if (hasMore1) {
do {
set.add(i1.current);
} while (i1.moveNext());
}
return set;
}
// Non-optimized version.
for (final target in this) {
if (!other.contains(target)) {
set.add(target);
}
}
return set;
}
}
AvlNode<V>? debugGetNode<V>(AvlTreeSet<V> treeset, V object) {
return treeset._getNode(object);
}
/// This iterator either starts at the beginning or end (see [TreeSet.iterator]
/// and [TreeSet.reverseIterator]) or from an anchor point in the set (see
/// [TreeSet.fromIterator]). When using fromIterator, the initial anchor point
/// is included in the first movement (either [moveNext] or [movePrevious]) but
/// can optionally be excluded in the constructor.
class TreeIterator<V>
implements
// ignore: deprecated_member_use
BidirectionalIterator<V> {
TreeIterator._(this.tree,
{this.reversed = false, this.inclusive = true, V? anchorObject})
: _anchorObject = anchorObject,
_modCountGuard = tree._modCount {
final anchor = _anchorObject;
if (anchor == null || tree.isEmpty) {
// If the anchor is far left or right, we're just a normal iterator.
_state = reversed ? _right : _left;
_moveNext = reversed ? _movePreviousNormal : _moveNextNormal;
_movePrevious = reversed ? _moveNextNormal : _movePreviousNormal;
return;
}
_state = _walk;
// Else we've got an anchor we have to worry about initializing from.
// This isn't known till the caller actually performs a previous/next.
_moveNext = () {
_current = tree._searchNearest(anchor,
option: reversed ? TreeSearch.LESS_THAN : TreeSearch.GREATER_THAN);
_moveNext = reversed ? _movePreviousNormal : _moveNextNormal;
_movePrevious = reversed ? _moveNextNormal : _movePreviousNormal;
if (_current == null) {
_state = reversed ? _left : _right;
} else if (tree.comparator(_current!.object, anchor) == 0 && !inclusive) {
_moveNext();
}
return _state == _walk;
};
_movePrevious = () {
_current = tree._searchNearest(anchor,
option: reversed ? TreeSearch.GREATER_THAN : TreeSearch.LESS_THAN);
_moveNext = reversed ? _movePreviousNormal : _moveNextNormal;
_movePrevious = reversed ? _moveNextNormal : _movePreviousNormal;
if (_current == null) {
_state = reversed ? _right : _left;
} else if (tree.comparator(_current!.object, anchor) == 0 && !inclusive) {
_movePrevious();
}
return _state == _walk;
};
}
static const _left = -1;
static const _walk = 0;
static const _right = 1;
final bool reversed;
final AvlTreeSet<V> tree;
final int _modCountGuard;
final V? _anchorObject;
final bool inclusive;
late bool Function() _moveNext;
late bool Function() _movePrevious;
late int _state;
_TreeNode<V>? _current;
@override
V get current {
// Prior to NNBD, this returned null when iteration was complete. In order
// to avoid a hard breaking change, we return "null as V" in that case so
// that if strong checking is not enabled or V is nullable, the existing
// behavior is preserved.
if (_state == _walk && _current != null) {
return _current?.object as V;
}
return null as V;
}
@override
bool moveNext() => _moveNext();
@override
bool movePrevious() => _movePrevious();
bool _moveNextNormal() {
if (_modCountGuard != tree._modCount) {
throw ConcurrentModificationError(tree);
}
if (_state == _right || tree.isEmpty) return false;
switch (_state) {
case _left:
_current = tree._root!.minimumNode;
_state = _walk;
return true;
case _walk:
default:
_current = _current!.successor;
if (_current == null) {
_state = _right;
}
return _state == _walk;
}
}
bool _movePreviousNormal() {
if (_modCountGuard != tree._modCount) {
throw ConcurrentModificationError(tree);
}
if (_state == _left || tree.isEmpty) return false;