-
Notifications
You must be signed in to change notification settings - Fork 3
/
RBTree.d
1270 lines (1186 loc) · 36.9 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
/*********************************************************
Copyright: (C) 2008-2010 by Steven Schveighoffer.
All rights reserved
License: Boost Software License version 1.0
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer, must
be included in all copies of the Software, in whole or in part, and all
derivative works of the Software, unless such copies or derivative works are
solely in the form of machine-executable object code generated by a source
language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
**********************************************************/
module dcollections.RBTree;
private import dcollections.model.Iterator;
private import dcollections.DefaultAllocator;
version(unittest) version = RBDoChecks;
version(RBDoChecks)
{
import std.stdio;
}
/**
* 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 RBNode!(V)* Node;
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(Node) left() inout
{
return _left;
}
/**
* Get the right child
*/
@property inout(Node) right() inout
{
return _right;
}
/**
* Get the parent
*/
@property inout(Node) 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);
}
body
{
// 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);
}
body
{
// 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);
}
body
{
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.
*/
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;
if(_left is null || _right is null)
{
ret = next;
}
else
{
//
// 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 = 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;
//
// set return value
//
ret = y;
}
// if this has less than 2 children, remove it
if(_left !is null)
x = _left;
else
x = _right;
// remove this from the tree at the end of the procedure
bool removeThis = false;
if(x is null)
{
// pretend this is a null node, remove this on finishing
x = &this;
removeThis = 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(removeThis)
{
//
// clear this node out of the tree
//
if(isLeftNode)
_parent.left = null;
else
_parent.right = null;
}
return ret;
}
/**
* Return the leftmost descendant of this node.
*/
@property inout(Node) 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(Node) 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(Node) 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(Node) 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 _dg(V v)
{
auto result = new RBNode!(V);
result.value = v;
return result;
}
return dup(&_dg);
}
}
/**
* Implementation of a red black tree.
*
* This uses RBNode to implement the tree.
*
* Set allowDuplicates to true to allow duplicate values to be inserted.
*/
struct RBTree(V, alias compareFunc, alias updateFunction, alias Allocator=DefaultAllocator, bool allowDuplicates=false, bool doUpdates=true)
{
/**
* Convenience aliases
*/
alias RBNode!(V).Node Node;
alias inout(RBNode!V)* ioNode;
alias const(RBNode!V)* cNode;
/**
* alias for the allocator
*/
alias Allocator!(RBNode!(V)) allocator;
/**
* The allocator
*/
allocator alloc;
/**
* The number of nodes in the tree
*/
size_t count;
/**
* The marker Node. This is the parent of the root Node.
*/
@property ioNode end() inout
{
return &_end;
}
/*
* the actual marker node, stored in the struct because it never changes.
*/
private RBNode!(V) _end;
/**
* Setup this RBTree.
*/
void setup()
{
}
/**
* Add a Node to the RBTree. Runs in O(lg(n)) time.
*
* Returns true if a new Node was added, false if it was not.
*
* This can also be used to update a value if it is already in the tree.
*/
bool add(V v)
{
Node added;
if(end.left is null)
end.left = added = allocate(v);
else
{
Node newParent = end.left;
while(true)
{
int cmpvalue = compareFunc(newParent.value, v);
if(cmpvalue == 0)
{
//
// found the value already in the tree. If duplicates are
// allowed, pretend the new value is greater than this value.
//
static if(allowDuplicates)
{
cmpvalue = -1;
}
else
{
static if(doUpdates)
updateFunction(newParent.value, v);
return false;
}
}
if(cmpvalue < 0)
{
Node nxt = newParent.right;
if(nxt is null)
{
//
// add to right of new parent
//
newParent.right = added = allocate(v);
break;
}
else
newParent = nxt;
}
else
{
Node nxt = newParent.left;
if(nxt is null)
{
//
// add to left of new parent
//
newParent.left = added = allocate(v);
break;
}
else
newParent = nxt;
}
}
}
//
// update the tree colors
//
added.setColor(end);
//
// did add a Node
//
count++;
version(RBDoChecks)
check();
return true;
}
/**
* Return the lowest-valued Node in the tree
*/
@property ioNode begin() inout
{
return end.leftmost;
}
/**
* Remove the Node from the tree. Returns the next Node in the tree.
*
* Do not call this with the marker (end) Node.
*/
Node remove(Node z)
in
{
assert(z !is end);
}
body
{
count--;
Node result = z.remove(end);
static if(allocator.freeNeeded)
alloc.free(z);
version(RBDoChecks)
check();
return result;
}
/**
* Find a Node in the tree with a given value. Returns end if no such
* Node exists.
*/
ioNode find(const(V) v) inout
{
static if(allowDuplicates)
{
//
// find the left-most v, this allows the pointer to traverse
// through all the v's.
//
ioNode cur = end;
ioNode n = end.left;
while(n !is null)
{
int cmpresult = compareFunc(n.value, v);
if(cmpresult < 0)
{
n = n.right;
}
else
{
if(cmpresult == 0)
cur = n;
n = n.left;
}
}
return cur;
}
else
{
ioNode n = end.left;
int cmpresult;
while(n !is null && (cmpresult = compareFunc(n.value, v)) != 0)
{
if(cmpresult < 0)
n = n.right;
else
n = n.left;
}
if(n is null)
return end;
return n;
}
}
/**
* Returns true if n is a node from this tree. Runs in O(lgn) time.
*/
bool belongs(cNode n) const
{
// check for null
if(!n)
return false;
// move up the tree to ensure the parent of the node is our end.
while(n.parent)
n = n.parent;
return n is end;
}
/**
* Determine if a and b both belong to this tree, and if so, record the
* relative ordering in order (order < 0 means a comes before b, order == 0
* means a is b, order > 0 means b comes before a)
*
* returning false means one or both of the nodes does not belong to this
* tree.
*
* This is used in slicing operations.
*/
bool positionCompare(cNode a, cNode b, out int order) const
{
if(a is null || b is null)
return false; // one or both of these don't belong
if(a is end)
{
if(b !is end)
{
order = 1;
return belongs(b);
}
else
{
order = 0;
return true;
}
}
else if(b is end)
{
order = -1;
return belongs(a);
}
// otherwise, both have values, compare the values.
order = compareFunc(a.value, b.value);
static if(allowDuplicates)
{
if(order == 0)
{
// allowing duplicates, so these might be different nodes.
// we want to determine which node comes first in the order,
// which is possible by converging the two nodes together into
// a common parent, then seeing which branch the two nodes came
// from.
if(a is b)
// trivial case, both are the same node.
return belongs(a);
// use special algo to get the height while checking for
// ownership.
size_t hta = 0;
auto n = a;
while(n.parent)
{
n = n.parent;
hta++;
}
if(n !is end)
return false;
size_t htb = 0;
n = b;
while(b.parent)
{
b = b.parent;
htb++;
}
if(n !is end)
return false;
// now, move the lowest node up to its parent, until both nodes
// converge.
while(hta | htb)
{
if(hta < htb)
{
if(b.parent is a)
{
order = b.isLeftNode ? 1 : -1;
return true;
}
b = b.parent;
htb--;
}
else
{
if(a.parent is b)
{
order = a.isLeftNode ? -1 : 1;
return true;
}
a = a.parent;
hta--;
}
}
assert(false, "Error, nodes should have converged!");
}
}
return belongs(a) && belongs(b);
}
/**
* clear all the nodes from the tree.
*/
void clear()
{
static if(allocator.freeNeeded)
{
alloc.freeAll();
}
end.left = null;
count = 0;
}
version(RBDoChecks)
{
/**
* Print the tree. This prints a sideways view of the tree in ASCII form,
* with the number of indentations representing the level of the nodes.
* It does not print values, only the tree structure and color of nodes.
*/
void printTree(Node n, int indent = 0)
{
if(indent > this.count)
// stop from recursing obviously too far
return;
if(n !is null)
{
printTree(n.right, indent + 2);
for(int i = 0; i < indent; i++)
write(".");
writeln(n.color == n.color.Black ? "B" : "R");
printTree(n.left, indent + 2);
}
else
{
for(int i = 0; i < indent; i++)
write(".");
writeln("N");
}
if(indent is 0)
writeln();
}
/**
* Check the tree for validity. This is called after every add or remove.
* This should only be enabled to debug the implementation of the RB Tree.
*/
void check()
{
//
// check implementation of the tree
//
bool dontPrint = false;
int recurse(Node n, string path)
{
if(path.length > this.count)
{
dontPrint = true;
throw new Exception("Tree structure is incorrect, recursion path has more elements than nodes exist");
}
if(n is null)