-
-
Notifications
You must be signed in to change notification settings - Fork 694
/
rbtree.d
2208 lines (1952 loc) · 61.1 KB
/
rbtree.d
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
/**
This module implements a red-black tree container.
This module is a submodule of $(MREF std, container).
Source: $(PHOBOSSRC std/container/rbtree.d)
Copyright: Red-black tree code copyright (C) 2008- by Steven Schveighoffer. Other code
copyright 2010- Andrei Alexandrescu. All rights reserved by the respective holders.
License: Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at $(HTTP
boost.org/LICENSE_1_0.txt)).
Authors: Steven Schveighoffer, $(HTTP erdani.com, Andrei Alexandrescu)
*/
module std.container.rbtree;
///
@safe pure unittest
{
import std.algorithm.comparison : equal;
import std.container.rbtree;
auto rbt = redBlackTree(3, 1, 4, 2, 5);
assert(rbt.front == 1);
assert(equal(rbt[], [1, 2, 3, 4, 5]));
rbt.removeKey(1, 4);
assert(equal(rbt[], [2, 3, 5]));
rbt.removeFront();
assert(equal(rbt[], [3, 5]));
rbt.insert([1, 2, 4]);
assert(equal(rbt[], [1, 2, 3, 4, 5]));
// Query bounds in O(log(n))
assert(rbt.lowerBound(3).equal([1, 2]));
assert(rbt.equalRange(3).equal([3]));
assert(rbt.upperBound(3).equal([4, 5]));
// A Red Black tree with the highest element at front:
import std.range : iota;
auto maxTree = redBlackTree!"a > b"(iota(5));
assert(equal(maxTree[], [4, 3, 2, 1, 0]));
// adding duplicates will not add them, but return 0
auto rbt2 = redBlackTree(1, 3);
assert(rbt2.insert(1) == 0);
assert(equal(rbt2[], [1, 3]));
assert(rbt2.insert(2) == 1);
// however you can allow duplicates
auto ubt = redBlackTree!true([0, 1, 0, 1]);
assert(equal(ubt[], [0, 0, 1, 1]));
}
import std.format;
import std.functional : binaryFun;
public import std.container.util;
version (unittest) debug = RBDoChecks;
//debug = RBDoChecks;
/*
* Implementation for a Red Black node for use in a Red Black Tree (see below)
*
* this implementation assumes we have a marker Node that is the parent of the
* root Node. This marker Node is not a valid Node, but marks the end of the
* collection. The root is the left child of the marker Node, so it is always
* last in the collection. The marker Node is passed in to the setColor
* function, and the Node which has this Node as its parent is assumed to be
* the root Node.
*
* A Red Black tree should have O(lg(n)) insertion, removal, and search time.
*/
struct RBNode(V)
{
/*
* Convenience alias
*/
alias Node = RBNode*;
private Node _left;
private Node _right;
private Node _parent;
/**
* The value held by this node
*/
V value;
/**
* Enumeration determining what color the node is. Null nodes are assumed
* to be black.
*/
enum Color : byte
{
Red,
Black
}
/**
* The color of the node.
*/
Color color;
/**
* Get the left child
*/
@property inout(RBNode)* left() inout
{
return _left;
}
/**
* Get the right child
*/
@property inout(RBNode)* right() inout
{
return _right;
}
/**
* Get the parent
*/
@property inout(RBNode)* parent() inout
{
return _parent;
}
/**
* Set the left child. Also updates the new child's parent node. This
* does not update the previous child.
*
* Returns newNode
*/
@property Node left(Node newNode)
{
_left = newNode;
if (newNode !is null)
newNode._parent = &this;
return newNode;
}
/**
* Set the right child. Also updates the new child's parent node. This
* does not update the previous child.
*
* Returns newNode
*/
@property Node right(Node newNode)
{
_right = newNode;
if (newNode !is null)
newNode._parent = &this;
return newNode;
}
// assume _left is not null
//
// performs rotate-right operation, where this is T, _right is R, _left is
// L, _parent is P:
//
// P P
// | -> |
// T L
// / \ / \
// L R a T
// / \ / \
// a b b R
//
/**
* Rotate right. This performs the following operations:
* - The left child becomes the parent of this node.
* - This node becomes the new parent's right child.
* - The old right child of the new parent becomes the left child of this
* node.
*/
Node rotateR()
in
{
assert(_left !is null);
}
do
{
// sets _left._parent also
if (isLeftNode)
parent.left = _left;
else
parent.right = _left;
Node tmp = _left._right;
// sets _parent also
_left.right = &this;
// sets tmp._parent also
left = tmp;
return &this;
}
// assumes _right is non null
//
// performs rotate-left operation, where this is T, _right is R, _left is
// L, _parent is P:
//
// P P
// | -> |
// T R
// / \ / \
// L R T b
// / \ / \
// a b L a
//
/**
* Rotate left. This performs the following operations:
* - The right child becomes the parent of this node.
* - This node becomes the new parent's left child.
* - The old left child of the new parent becomes the right child of this
* node.
*/
Node rotateL()
in
{
assert(_right !is null);
}
do
{
// sets _right._parent also
if (isLeftNode)
parent.left = _right;
else
parent.right = _right;
Node tmp = _right._left;
// sets _parent also
_right.left = &this;
// sets tmp._parent also
right = tmp;
return &this;
}
/**
* Returns true if this node is a left child.
*
* Note that this should always return a value because the root has a
* parent which is the marker node.
*/
@property bool isLeftNode() const
in
{
assert(_parent !is null);
}
do
{
return _parent._left is &this;
}
/**
* Set the color of the node after it is inserted. This performs an
* update to the whole tree, possibly rotating nodes to keep the Red-Black
* properties correct. This is an O(lg(n)) operation, where n is the
* number of nodes in the tree.
*
* end is the marker node, which is the parent of the topmost valid node.
*/
void setColor(Node end)
{
// test against the marker node
if (_parent !is end)
{
if (_parent.color == Color.Red)
{
Node cur = &this;
while (true)
{
// because root is always black, _parent._parent always exists
if (cur._parent.isLeftNode)
{
// parent is left node, y is 'uncle', could be null
Node y = cur._parent._parent._right;
if (y !is null && y.color == Color.Red)
{
cur._parent.color = Color.Black;
y.color = Color.Black;
cur = cur._parent._parent;
if (cur._parent is end)
{
// root node
cur.color = Color.Black;
break;
}
else
{
// not root node
cur.color = Color.Red;
if (cur._parent.color == Color.Black)
// satisfied, exit the loop
break;
}
}
else
{
if (!cur.isLeftNode)
cur = cur._parent.rotateL();
cur._parent.color = Color.Black;
cur = cur._parent._parent.rotateR();
cur.color = Color.Red;
// tree should be satisfied now
break;
}
}
else
{
// parent is right node, y is 'uncle'
Node y = cur._parent._parent._left;
if (y !is null && y.color == Color.Red)
{
cur._parent.color = Color.Black;
y.color = Color.Black;
cur = cur._parent._parent;
if (cur._parent is end)
{
// root node
cur.color = Color.Black;
break;
}
else
{
// not root node
cur.color = Color.Red;
if (cur._parent.color == Color.Black)
// satisfied, exit the loop
break;
}
}
else
{
if (cur.isLeftNode)
cur = cur._parent.rotateR();
cur._parent.color = Color.Black;
cur = cur._parent._parent.rotateL();
cur.color = Color.Red;
// tree should be satisfied now
break;
}
}
}
}
}
else
{
//
// this is the root node, color it black
//
color = Color.Black;
}
}
/**
* Remove this node from the tree. The 'end' node is used as the marker
* which is root's parent. Note that this cannot be null!
*
* Returns the next highest valued node in the tree after this one, or end
* if this was the highest-valued node.
*/
Node remove(Node end)
{
//
// remove this node from the tree, fixing the color if necessary.
//
Node x;
Node ret = next;
// if this node has 2 children
if (_left !is null && _right !is null)
{
//
// normally, we can just swap this node's and y's value, but
// because an iterator could be pointing to y and we don't want to
// disturb it, we swap this node and y's structure instead. This
// can also be a benefit if the value of the tree is a large
// struct, which takes a long time to copy.
//
Node yp, yl, yr;
Node y = ret; // y = next
yp = y._parent;
yl = y._left;
yr = y._right;
auto yc = y.color;
auto isyleft = y.isLeftNode;
//
// replace y's structure with structure of this node.
//
if (isLeftNode)
_parent.left = y;
else
_parent.right = y;
//
// need special case so y doesn't point back to itself
//
y.left = _left;
if (_right is y)
y.right = &this;
else
y.right = _right;
y.color = color;
//
// replace this node's structure with structure of y.
//
left = yl;
right = yr;
if (_parent !is y)
{
if (isyleft)
yp.left = &this;
else
yp.right = &this;
}
color = yc;
}
// if this has less than 2 children, remove it
if (_left !is null)
x = _left;
else
x = _right;
bool deferedUnlink = false;
if (x is null)
{
// pretend this is a null node, defer unlinking the node
x = &this;
deferedUnlink = true;
}
else if (isLeftNode)
_parent.left = x;
else
_parent.right = x;
// if the color of this is black, then it needs to be fixed
if (color == color.Black)
{
// need to recolor the tree.
while (x._parent !is end && x.color == Node.Color.Black)
{
if (x.isLeftNode)
{
// left node
Node w = x._parent._right;
if (w.color == Node.Color.Red)
{
w.color = Node.Color.Black;
x._parent.color = Node.Color.Red;
x._parent.rotateL();
w = x._parent._right;
}
Node wl = w.left;
Node wr = w.right;
if ((wl is null || wl.color == Node.Color.Black) &&
(wr is null || wr.color == Node.Color.Black))
{
w.color = Node.Color.Red;
x = x._parent;
}
else
{
if (wr is null || wr.color == Node.Color.Black)
{
// wl cannot be null here
wl.color = Node.Color.Black;
w.color = Node.Color.Red;
w.rotateR();
w = x._parent._right;
}
w.color = x._parent.color;
x._parent.color = Node.Color.Black;
w._right.color = Node.Color.Black;
x._parent.rotateL();
x = end.left; // x = root
}
}
else
{
// right node
Node w = x._parent._left;
if (w.color == Node.Color.Red)
{
w.color = Node.Color.Black;
x._parent.color = Node.Color.Red;
x._parent.rotateR();
w = x._parent._left;
}
Node wl = w.left;
Node wr = w.right;
if ((wl is null || wl.color == Node.Color.Black) &&
(wr is null || wr.color == Node.Color.Black))
{
w.color = Node.Color.Red;
x = x._parent;
}
else
{
if (wl is null || wl.color == Node.Color.Black)
{
// wr cannot be null here
wr.color = Node.Color.Black;
w.color = Node.Color.Red;
w.rotateL();
w = x._parent._left;
}
w.color = x._parent.color;
x._parent.color = Node.Color.Black;
w._left.color = Node.Color.Black;
x._parent.rotateR();
x = end.left; // x = root
}
}
}
x.color = Node.Color.Black;
}
if (deferedUnlink)
{
//
// unlink this node from the tree
//
if (isLeftNode)
_parent.left = null;
else
_parent.right = null;
}
// clean references to help GC - Bugzilla 12915
_left = _right = _parent = null;
return ret;
}
/**
* Return the leftmost descendant of this node.
*/
@property inout(RBNode)* leftmost() inout
{
inout(RBNode)* result = &this;
while (result._left !is null)
result = result._left;
return result;
}
/**
* Return the rightmost descendant of this node
*/
@property inout(RBNode)* rightmost() inout
{
inout(RBNode)* result = &this;
while (result._right !is null)
result = result._right;
return result;
}
/**
* Returns the next valued node in the tree.
*
* You should never call this on the marker node, as it is assumed that
* there is a valid next node.
*/
@property inout(RBNode)* next() inout
{
inout(RBNode)* n = &this;
if (n.right is null)
{
while (!n.isLeftNode)
n = n._parent;
return n._parent;
}
else
return n.right.leftmost;
}
/**
* Returns the previous valued node in the tree.
*
* You should never call this on the leftmost node of the tree as it is
* assumed that there is a valid previous node.
*/
@property inout(RBNode)* prev() inout
{
inout(RBNode)* n = &this;
if (n.left is null)
{
while (n.isLeftNode)
n = n._parent;
return n._parent;
}
else
return n.left.rightmost;
}
Node dup(scope Node delegate(V v) alloc)
{
//
// duplicate this and all child nodes
//
// The recursion should be lg(n), so we shouldn't have to worry about
// stack size.
//
Node copy = alloc(value);
copy.color = color;
if (_left !is null)
copy.left = _left.dup(alloc);
if (_right !is null)
copy.right = _right.dup(alloc);
return copy;
}
Node dup()
{
Node copy = new RBNode!V(null, null, null, value);
copy.color = color;
if (_left !is null)
copy.left = _left.dup();
if (_right !is null)
copy.right = _right.dup();
return copy;
}
}
//constness checks
@safe pure unittest
{
const RBNode!int n;
static assert(is(typeof(n.leftmost)));
static assert(is(typeof(n.rightmost)));
static assert(is(typeof(n.next)));
static assert(is(typeof(n.prev)));
}
private struct RBRange(N)
{
alias Node = N;
alias Elem = typeof(Node.value);
private Node _begin;
private Node _end;
private this(Node b, Node e)
{
_begin = b;
_end = e;
}
/**
* Returns `true` if the range is _empty
*/
@property bool empty() const
{
return _begin is _end;
}
/**
* Returns the first element in the range
*/
@property Elem front()
{
return _begin.value;
}
/**
* Returns the last element in the range
*/
@property Elem back()
{
return _end.prev.value;
}
/**
* pop the front element from the range
*
* Complexity: amortized $(BIGOH 1)
*/
void popFront()
{
_begin = _begin.next;
}
/**
* pop the back element from the range
*
* Complexity: amortized $(BIGOH 1)
*/
void popBack()
{
_end = _end.prev;
}
/**
* Trivial _save implementation, needed for `isForwardRange`.
*/
@property RBRange save()
{
return this;
}
}
/**
* Implementation of a $(LINK2 https://en.wikipedia.org/wiki/Red%E2%80%93black_tree,
* red-black tree) container.
*
* All inserts, removes, searches, and any function in general has complexity
* of $(BIGOH lg(n)).
*
* To use a different comparison than $(D "a < b"), pass a different operator string
* that can be used by $(REF binaryFun, std,functional), or pass in a
* function, delegate, functor, or any type where $(D less(a, b)) results in a `bool`
* value.
*
* Note that less should produce a strict ordering. That is, for two unequal
* elements `a` and `b`, $(D less(a, b) == !less(b, a)). $(D less(a, a)) should
* always equal `false`.
*
* If `allowDuplicates` is set to `true`, then inserting the same element more than
* once continues to add more elements. If it is `false`, duplicate elements are
* ignored on insertion. If duplicates are allowed, then new elements are
* inserted after all existing duplicate elements.
*/
final class RedBlackTree(T, alias less = "a < b", bool allowDuplicates = false)
if (is(typeof(binaryFun!less(T.init, T.init))))
{
import std.meta : allSatisfy;
import std.range : Take;
import std.range.primitives : isInputRange, walkLength;
import std.traits : isIntegral, isDynamicArray, isImplicitlyConvertible;
alias _less = binaryFun!less;
version (unittest)
{
static if (is(typeof(less) == string))
{
private enum doUnittest = isIntegral!T && (less == "a < b" || less == "a > b");
}
else
enum doUnittest = false;
// note, this must be final so it does not affect the vtable layout
bool arrayEqual(T[] arr)
{
if (walkLength(this[]) == arr.length)
{
foreach (v; arr)
{
if (!(v in this))
return false;
}
return true;
}
return false;
}
}
else
{
private enum doUnittest = false;
}
/**
* Element type for the tree
*/
alias Elem = T;
// used for convenience
private alias RBNode = .RBNode!Elem;
private alias Node = RBNode.Node;
private Node _end;
private Node _begin;
private size_t _length;
private void _setup()
{
assert(!_end); //Make sure that _setup isn't run more than once.
_begin = _end = allocate();
}
static private Node allocate()
{
return new RBNode;
}
static private Node allocate(Elem v)
{
return new RBNode(null, null, null, v);
}
/**
* The range types for `RedBlackTree`
*/
alias Range = RBRange!(RBNode*);
alias ConstRange = RBRange!(const(RBNode)*); /// Ditto
alias ImmutableRange = RBRange!(immutable(RBNode)*); /// Ditto
static if (doUnittest) @safe pure unittest
{
import std.algorithm.comparison : equal;
import std.range.primitives;
auto ts = new RedBlackTree(1, 2, 3, 4, 5);
assert(ts.length == 5);
auto r = ts[];
static if (less == "a < b")
auto vals = [1, 2, 3, 4, 5];
else
auto vals = [5, 4, 3, 2, 1];
assert(equal(r, vals));
assert(r.front == vals.front);
assert(r.back != r.front);
auto oldfront = r.front;
auto oldback = r.back;
r.popFront();
r.popBack();
assert(r.front != r.back);
assert(r.front != oldfront);
assert(r.back != oldback);
assert(ts.length == 5);
}
// find a node based on an element value
private inout(RBNode)* _find(Elem e) inout
{
static if (allowDuplicates)
{
inout(RBNode)* cur = _end.left;
inout(RBNode)* result = null;
while (cur)
{
if (_less(cur.value, e))
cur = cur.right;
else if (_less(e, cur.value))
cur = cur.left;
else
{
// want to find the left-most element
result = cur;
cur = cur.left;
}
}
return result;
}
else
{
inout(RBNode)* cur = _end.left;
while (cur)
{
if (_less(cur.value, e))
cur = cur.right;
else if (_less(e, cur.value))
cur = cur.left;
else
return cur;
}
return null;
}
}
/* add an element to the tree, returns the node added, or the existing node
* if it has already been added and allowDuplicates is false
* Returns:
* true if node was added
*/
private bool _add(return Elem n)
{
Node result;
static if (!allowDuplicates)
bool added = true;
if (!_end.left)
{
result = allocate(n);
(() @trusted { _end.left = _begin = result; }) ();
}
else
{
Node newParent = _end.left;
Node nxt;
while (true)
{
if (_less(n, newParent.value))
{
nxt = newParent.left;
if (nxt is null)
{
//
// add to right of new parent
//
result = allocate(n);
(() @trusted { newParent.left = result; }) ();
break;
}
}
else
{
static if (!allowDuplicates)
{
if (!_less(newParent.value, n))
{
result = newParent;
added = false;
break;
}
}
nxt = newParent.right;
if (nxt is null)
{
//
// add to right of new parent
//
result = allocate(n);
(() @trusted { newParent.right = result; }) ();
break;
}
}
newParent = nxt;
}
if (_begin.left)
_begin = _begin.left;
}
static if (allowDuplicates)
{
result.setColor(_end);
debug(RBDoChecks)
check();
++_length;
return true;
}
else
{
if (added)
{
++_length;
result.setColor(_end);
}
debug(RBDoChecks)
check();
return added;
}
}
/**
* Check if any elements exist in the container. Returns `false` if at least
* one element exists.
*/
@property bool empty()
{
return _end.left is null;
}
/++
Returns the number of elements in the container.
Complexity: $(BIGOH 1).
+/
@property size_t length() const
{
return _length;
}
/**
* Duplicate this container. The resulting container contains a shallow
* copy of the elements.
*
* Complexity: $(BIGOH n)
*/
@property RedBlackTree dup()
{
return new RedBlackTree(_end.dup(), _length);
}
static if (doUnittest) @safe pure unittest
{
import std.algorithm.comparison : equal;
auto ts = new RedBlackTree(1, 2, 3, 4, 5);
assert(ts.length == 5);
auto ts2 = ts.dup;
assert(ts2.length == 5);
assert(equal(ts[], ts2[]));
ts2.insert(cast(Elem) 6);
assert(!equal(ts[], ts2[]));