2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef GrRedBlackTree_DEFINED
9 #define GrRedBlackTree_DEFINED
17 bool operator()(const T& a, const T& b) const { return a < b; }
23 bool operator()(const T* a, const T* b) const { return *a < *b; }
27 * In debug build this will cause full traversals of the tree when the validate
28 * is called on insert and remove. Useful for debugging but very slow.
30 #define DEEP_VALIDATE 0
33 * A sorted tree that uses the red-black tree algorithm. Allows duplicate
34 * entries. Data is of type T and is compared using functor C. A single C object
35 * will be created and used for all comparisons.
37 template <typename T, typename C = GrLess<T> >
38 class GrRedBlackTree : public SkNoncopyable {
41 * Creates an empty tree.
44 virtual ~GrRedBlackTree();
47 * Class used to iterater through the tree. The valid range of the tree
48 * is given by [begin(), end()). It is legal to dereference begin() but not
49 * end(). The iterator has preincrement and predecrement operators, it is
50 * legal to decerement end() if the tree is not empty to get the last
51 * element. However, a last() helper is provided.
56 * Add an element to the tree. Duplicates are allowed.
57 * @param t the item to add.
58 * @return an iterator to the item.
60 Iter insert(const T& t);
63 * Removes all items in the tree.
68 * @return true if there are no items in the tree, false otherwise.
70 bool empty() const {return 0 == fCount;}
73 * @return the number of items in the tree.
75 int count() const {return fCount;}
78 * @return an iterator to the first item in sorted order, or end() if empty
82 * Gets the last valid iterator. This is always valid, even on an empty.
83 * However, it can never be dereferenced. Useful as a loop terminator.
84 * @return an iterator that is just beyond the last item in sorted order.
88 * @return an iterator that to the last item in sorted order, or end() if
94 * Finds an occurrence of an item.
95 * @param t the item to find.
96 * @return an iterator to a tree element equal to t or end() if none exists.
98 Iter find(const T& t);
100 * Finds the first of an item in iterator order.
101 * @param t the item to find.
102 * @return an iterator to the first element equal to t or end() if
105 Iter findFirst(const T& t);
107 * Finds the last of an item in iterator order.
108 * @param t the item to find.
109 * @return an iterator to the last element equal to t or end() if
112 Iter findLast(const T& t);
114 * Gets the number of items in the tree equal to t.
115 * @param t the item to count.
116 * @return number of items equal to t in the tree
118 int countOf(const T& t) const;
121 * Removes the item indicated by an iterator. The iterator will not be valid
124 * @param iter iterator of item to remove. Must be valid (not end()).
126 void remove(const Iter& iter) { deleteAtNode(iter.fN); }
147 void rotateRight(Node* n);
148 void rotateLeft(Node* n);
150 static Node* SuccessorNode(Node* x);
151 static Node* PredecessorNode(Node* x);
153 void deleteAtNode(Node* x);
154 static void RecursiveDelete(Node* x);
156 int onCountOf(const Node* n, const T& t) const;
159 void validate() const;
160 int checkNode(Node* n, int* blackHeight) const;
161 // checks relationship between a node and its children. allowRedRed means
162 // node may be in an intermediate state where a red parent has a red child.
163 bool validateChildRelations(const Node* n, bool allowRedRed) const;
164 // place to stick break point if validateChildRelations is failing.
165 bool validateChildRelationsFailed() const { return false; }
167 void validate() const {}
178 template <typename T, typename C>
179 class GrRedBlackTree<T,C>::Iter {
182 Iter(const Iter& i) {fN = i.fN; fTree = i.fTree;}
183 Iter& operator =(const Iter& i) {
188 // altering the sort value of the item using this method will cause
190 T& operator *() const { return fN->fItem; }
191 bool operator ==(const Iter& i) const {
192 return fN == i.fN && fTree == i.fTree;
194 bool operator !=(const Iter& i) const { return !(*this == i); }
195 Iter& operator ++() {
196 SkASSERT(*this != fTree->end());
197 fN = SuccessorNode(fN);
200 Iter& operator --() {
201 SkASSERT(*this != fTree->begin());
203 fN = PredecessorNode(fN);
205 *this = fTree->last();
211 friend class GrRedBlackTree;
212 explicit Iter(Node* n, GrRedBlackTree* tree) {
217 GrRedBlackTree* fTree;
220 template <typename T, typename C>
221 GrRedBlackTree<T,C>::GrRedBlackTree() : fComp() {
229 template <typename T, typename C>
230 GrRedBlackTree<T,C>::~GrRedBlackTree() {
231 RecursiveDelete(fRoot);
234 template <typename T, typename C>
235 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::begin() {
236 return Iter(fFirst, this);
239 template <typename T, typename C>
240 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::end() {
241 return Iter(NULL, this);
244 template <typename T, typename C>
245 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::last() {
246 return Iter(fLast, this);
249 template <typename T, typename C>
250 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::find(const T& t) {
253 if (fComp(t, n->fItem)) {
254 n = n->fChildren[kLeft_Child];
256 if (!fComp(n->fItem, t)) {
257 return Iter(n, this);
259 n = n->fChildren[kRight_Child];
265 template <typename T, typename C>
266 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::findFirst(const T& t) {
268 Node* leftMost = NULL;
270 if (fComp(t, n->fItem)) {
271 n = n->fChildren[kLeft_Child];
273 if (!fComp(n->fItem, t)) {
274 // found one. check if another in left subtree.
276 n = n->fChildren[kLeft_Child];
278 n = n->fChildren[kRight_Child];
282 return Iter(leftMost, this);
285 template <typename T, typename C>
286 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::findLast(const T& t) {
288 Node* rightMost = NULL;
290 if (fComp(t, n->fItem)) {
291 n = n->fChildren[kLeft_Child];
293 if (!fComp(n->fItem, t)) {
294 // found one. check if another in right subtree.
297 n = n->fChildren[kRight_Child];
300 return Iter(rightMost, this);
303 template <typename T, typename C>
304 int GrRedBlackTree<T,C>::countOf(const T& t) const {
305 return onCountOf(fRoot, t);
308 template <typename T, typename C>
309 int GrRedBlackTree<T,C>::onCountOf(const Node* n, const T& t) const {
310 // this is count*log(n) :(
312 if (fComp(t, n->fItem)) {
313 n = n->fChildren[kLeft_Child];
315 if (!fComp(n->fItem, t)) {
317 count += onCountOf(n->fChildren[kLeft_Child], t);
318 count += onCountOf(n->fChildren[kRight_Child], t);
321 n = n->fChildren[kRight_Child];
328 template <typename T, typename C>
329 void GrRedBlackTree<T,C>::reset() {
330 RecursiveDelete(fRoot);
337 template <typename T, typename C>
338 typename GrRedBlackTree<T,C>::Iter GrRedBlackTree<T,C>::insert(const T& t) {
343 Node* x = SkNEW(Node);
344 x->fChildren[kLeft_Child] = NULL;
345 x->fChildren[kRight_Child] = NULL;
348 Node* returnNode = x;
353 Child pc = kLeft_Child; // suppress uninit warning
354 Child gpc = kLeft_Child;
360 pc = fComp(x->fItem, n->fItem) ? kLeft_Child : kRight_Child;
361 first = first && kLeft_Child == pc;
362 last = last && kRight_Child == pc;
365 n = p->fChildren[pc];
376 x->fColor = kBlack_Color;
378 SkASSERT(1 == fCount);
379 return Iter(returnNode, this);
381 p->fChildren[pc] = x;
382 x->fColor = kRed_Color;
386 // assumptions at loop start.
388 SkASSERT(kRed_Color == x->fColor);
389 // can't have a grandparent but no parent.
390 SkASSERT(!(NULL != gp && NULL == p));
391 // make sure pc and gpc are correct
392 SkASSERT(NULL == p || p->fChildren[pc] == x);
393 SkASSERT(NULL == gp || gp->fChildren[gpc] == p);
395 // if x's parent is black then we didn't violate any of the
396 // red/black properties when we added x as red.
397 if (kBlack_Color == p->fColor) {
398 return Iter(returnNode, this);
400 // gp must be valid because if p was the root then it is black
401 SkASSERT(NULL != gp);
402 // gp must be black since it's child, p, is red.
403 SkASSERT(kBlack_Color == gp->fColor);
406 // x and its parent are red, violating red-black property.
407 Node* u = gp->fChildren[1-gpc];
408 // if x's uncle (p's sibling) is also red then we can flip
409 // p and u to black and make gp red. But then we have to recurse
410 // up to gp since it's parent may also be red.
411 if (NULL != u && kRed_Color == u->fColor) {
412 p->fColor = kBlack_Color;
413 u->fColor = kBlack_Color;
414 gp->fColor = kRed_Color;
418 // x (prev gp) is the root, color it black and be done.
419 SkASSERT(fRoot == x);
420 x->fColor = kBlack_Color;
422 return Iter(returnNode, this);
425 pc = (p->fChildren[kLeft_Child] == x) ? kLeft_Child :
428 gpc = (gp->fChildren[kLeft_Child] == p) ? kLeft_Child :
434 // Here p is red but u is black and we still have to resolve the fact
435 // that x and p are both red.
436 SkASSERT(NULL == gp->fChildren[1-gpc] || kBlack_Color == gp->fChildren[1-gpc]->fColor);
437 SkASSERT(kRed_Color == x->fColor);
438 SkASSERT(kRed_Color == p->fColor);
439 SkASSERT(kBlack_Color == gp->fColor);
441 // make x be on the same side of p as p is of gp. If it isn't already
442 // the case then rotate x up to p and swap their labels.
444 if (kRight_Child == pc) {
458 // we now rotate gp down, pulling up p to be it's new parent.
459 // gp's child, u, that is not affected we know to be black. gp's new
460 // child is p's previous child (x's pre-rotation sibling) which must be
461 // black since p is red.
462 SkASSERT(NULL == p->fChildren[1-pc] ||
463 kBlack_Color == p->fChildren[1-pc]->fColor);
464 // Since gp's two children are black it can become red if p is made
465 // black. This leaves the black-height of both of p's new subtrees
466 // preserved and removes the red/red parent child relationship.
467 p->fColor = kBlack_Color;
468 gp->fColor = kRed_Color;
469 if (kLeft_Child == pc) {
475 return Iter(returnNode, this);
479 template <typename T, typename C>
480 void GrRedBlackTree<T,C>::rotateRight(Node* n) {
489 Node* d = n->fParent;
490 Node* s = n->fChildren[kLeft_Child];
492 Node* b = s->fChildren[kRight_Child];
495 Child c = d->fChildren[kLeft_Child] == n ? kLeft_Child :
499 SkASSERT(fRoot == n);
503 s->fChildren[kRight_Child] = n;
505 n->fChildren[kLeft_Child] = b;
510 GR_DEBUGASSERT(validateChildRelations(d, true));
511 GR_DEBUGASSERT(validateChildRelations(s, true));
512 GR_DEBUGASSERT(validateChildRelations(n, false));
513 GR_DEBUGASSERT(validateChildRelations(n->fChildren[kRight_Child], true));
514 GR_DEBUGASSERT(validateChildRelations(b, true));
515 GR_DEBUGASSERT(validateChildRelations(s->fChildren[kLeft_Child], true));
518 template <typename T, typename C>
519 void GrRedBlackTree<T,C>::rotateLeft(Node* n) {
521 Node* d = n->fParent;
522 Node* s = n->fChildren[kRight_Child];
524 Node* b = s->fChildren[kLeft_Child];
527 Child c = d->fChildren[kRight_Child] == n ? kRight_Child :
531 SkASSERT(fRoot == n);
535 s->fChildren[kLeft_Child] = n;
537 n->fChildren[kRight_Child] = b;
542 GR_DEBUGASSERT(validateChildRelations(d, true));
543 GR_DEBUGASSERT(validateChildRelations(s, true));
544 GR_DEBUGASSERT(validateChildRelations(n, true));
545 GR_DEBUGASSERT(validateChildRelations(n->fChildren[kLeft_Child], true));
546 GR_DEBUGASSERT(validateChildRelations(b, true));
547 GR_DEBUGASSERT(validateChildRelations(s->fChildren[kRight_Child], true));
550 template <typename T, typename C>
551 typename GrRedBlackTree<T,C>::Node* GrRedBlackTree<T,C>::SuccessorNode(Node* x) {
553 if (NULL != x->fChildren[kRight_Child]) {
554 x = x->fChildren[kRight_Child];
555 while (NULL != x->fChildren[kLeft_Child]) {
556 x = x->fChildren[kLeft_Child];
560 while (NULL != x->fParent && x == x->fParent->fChildren[kRight_Child]) {
566 template <typename T, typename C>
567 typename GrRedBlackTree<T,C>::Node* GrRedBlackTree<T,C>::PredecessorNode(Node* x) {
569 if (NULL != x->fChildren[kLeft_Child]) {
570 x = x->fChildren[kLeft_Child];
571 while (NULL != x->fChildren[kRight_Child]) {
572 x = x->fChildren[kRight_Child];
576 while (NULL != x->fParent && x == x->fParent->fChildren[kLeft_Child]) {
582 template <typename T, typename C>
583 void GrRedBlackTree<T,C>::deleteAtNode(Node* x) {
588 bool hasLeft = NULL != x->fChildren[kLeft_Child];
589 bool hasRight = NULL != x->fChildren[kRight_Child];
590 Child c = hasLeft ? kLeft_Child : kRight_Child;
592 if (hasLeft && hasRight) {
593 // first and last can't have two children.
594 SkASSERT(fFirst != x);
595 SkASSERT(fLast != x);
596 // if x is an interior node then we find it's successor
598 Node* s = x->fChildren[kRight_Child];
599 while (NULL != s->fChildren[kLeft_Child]) {
600 s = s->fChildren[kLeft_Child];
603 // this might be expensive relative to swapping node ptrs around.
608 } else if (NULL == x->fParent) {
609 // if x was the root we just replace it with its child and make
610 // the new root (if the tree is not empty) black.
611 SkASSERT(fRoot == x);
612 fRoot = x->fChildren[c];
614 fRoot->fParent = NULL;
615 fRoot->fColor = kBlack_Color;
617 SkASSERT(c == kLeft_Child);
619 } else if (x == fFirst) {
620 SkASSERT(c == kRight_Child);
624 SkASSERT(fFirst == fLast && x == fFirst);
627 SkASSERT(0 == fCount);
635 Node* p = x->fParent;
636 pc = p->fChildren[kLeft_Child] == x ? kLeft_Child : kRight_Child;
638 if (NULL == x->fChildren[c]) {
641 SkASSERT(p == PredecessorNode(x));
642 } else if (fFirst == x) {
644 SkASSERT(p == SuccessorNode(x));
646 // x has two implicit black children.
647 Color xcolor = x->fColor;
648 p->fChildren[pc] = NULL;
651 // when x is red it can be with an implicit black leaf without
652 // violating any of the red-black tree properties.
653 if (kRed_Color == xcolor) {
657 // s is p's other child (x's sibling)
658 Node* s = p->fChildren[1-pc];
660 //s cannot be an implicit black node because the original
661 // black-height at x was >= 2 and s's black-height must equal the
662 // initial black height of x.
664 SkASSERT(p == s->fParent);
673 // When we start this loop x may already be deleted it is/was
674 // p's child on its pc side. x's children are/were black. The
675 // first time through the loop they are implict children.
676 // On later passes we will be walking up the tree and they will
678 // The x side of p has a black-height that is one less than the
679 // s side. It must be rebalanced.
681 SkASSERT(p == s->fParent);
682 SkASSERT(NULL == x || x->fParent == p);
684 //sl and sr are s's children, which may be implicit.
685 sl = s->fChildren[kLeft_Child];
686 sr = s->fChildren[kRight_Child];
688 // if the s is red we will rotate s and p, swap their colors so
689 // that x's new sibling is black
690 if (kRed_Color == s->fColor) {
691 // if s is red then it's parent must be black.
692 SkASSERT(kBlack_Color == p->fColor);
693 // s's children must also be black since s is red. They can't
694 // be implicit since s is red and it's black-height is >= 2.
695 SkASSERT(NULL != sl && kBlack_Color == sl->fColor);
696 SkASSERT(NULL != sr && kBlack_Color == sr->fColor);
697 p->fColor = kRed_Color;
698 s->fColor = kBlack_Color;
699 if (kLeft_Child == pc) {
706 sl = s->fChildren[kLeft_Child];
707 sr = s->fChildren[kRight_Child];
709 // x and s are now both black.
710 SkASSERT(kBlack_Color == s->fColor);
711 SkASSERT(NULL == x || kBlack_Color == x->fColor);
712 SkASSERT(p == s->fParent);
713 SkASSERT(NULL == x || p == x->fParent);
715 // when x is deleted its subtree will have reduced black-height.
716 slRed = (NULL != sl && kRed_Color == sl->fColor);
717 srRed = (NULL != sr && kRed_Color == sr->fColor);
718 if (!slRed && !srRed) {
719 // if s can be made red that will balance out x's removal
720 // to make both subtrees of p have the same black-height.
721 if (kBlack_Color == p->fColor) {
722 s->fColor = kRed_Color;
723 // now subtree at p has black-height of one less than
724 // p's parent's other child's subtree. We move x up to
725 // p and go through the loop again. At the top of loop
726 // we assumed x and x's children are black, which holds
728 // if p is the root there is no other subtree to balance
733 SkASSERT(fRoot == x);
737 pc = p->fChildren[kLeft_Child] == x ? kLeft_Child :
741 s = p->fChildren[1-pc];
743 SkASSERT(p == s->fParent);
745 } else if (kRed_Color == p->fColor) {
746 // we can make p black and s red. This balance out p's
747 // two subtrees and keep the same black-height as it was
748 // before the delete.
749 s->fColor = kRed_Color;
750 p->fColor = kBlack_Color;
757 // if we made it here one or both of sl and sr is red.
758 // s and x are black. We make sure that a red child is on
759 // the same side of s as s is of p.
760 SkASSERT(slRed || srRed);
761 if (kLeft_Child == pc && !srRed) {
762 s->fColor = kRed_Color;
763 sl->fColor = kBlack_Color;
767 //sl = s->fChildren[kLeft_Child]; don't need this
768 } else if (kRight_Child == pc && !slRed) {
769 s->fColor = kRed_Color;
770 sr->fColor = kBlack_Color;
774 //sr = s->fChildren[kRight_Child]; don't need this
776 // now p is either red or black, x and s are red and s's 1-pc
778 // We rotate p towards x, pulling s up to replace p. We make
779 // p be black and s takes p's old color.
780 // Whether p was red or black, we've increased its pc subtree
781 // rooted at x by 1 (balancing the imbalance at the start) and
782 // we've also its subtree rooted at s's black-height by 1. This
783 // can be balanced by making s's red child be black.
784 s->fColor = p->fColor;
785 p->fColor = kBlack_Color;
786 if (kLeft_Child == pc) {
787 SkASSERT(NULL != sr && kRed_Color == sr->fColor);
788 sr->fColor = kBlack_Color;
791 SkASSERT(NULL != sl && kRed_Color == sl->fColor);
792 sl->fColor = kBlack_Color;
797 // x has exactly one implicit black child. x cannot be red.
798 // Proof by contradiction: Assume X is red. Let c0 be x's implicit
799 // child and c1 be its non-implicit child. c1 must be black because
800 // red nodes always have two black children. Then the two subtrees
801 // of x rooted at c0 and c1 will have different black-heights.
802 SkASSERT(kBlack_Color == x->fColor);
803 // So we know x is black and has one implicit black child, c0. c1
804 // must be red, otherwise the subtree at c1 will have a different
805 // black-height than the subtree rooted at c0.
806 SkASSERT(kRed_Color == x->fChildren[c]->fColor);
807 // replace x with c1, making c1 black, preserves all red-black tree
809 Node* c1 = x->fChildren[c];
811 SkASSERT(c == kRight_Child);
813 while (NULL != fFirst->fChildren[kLeft_Child]) {
814 fFirst = fFirst->fChildren[kLeft_Child];
816 SkASSERT(fFirst == SuccessorNode(x));
817 } else if (x == fLast) {
818 SkASSERT(c == kLeft_Child);
820 while (NULL != fLast->fChildren[kRight_Child]) {
821 fLast = fLast->fChildren[kRight_Child];
823 SkASSERT(fLast == PredecessorNode(x));
826 p->fChildren[pc] = c1;
827 c1->fColor = kBlack_Color;
834 template <typename T, typename C>
835 void GrRedBlackTree<T,C>::RecursiveDelete(Node* x) {
837 RecursiveDelete(x->fChildren[kLeft_Child]);
838 RecursiveDelete(x->fChildren[kRight_Child]);
844 template <typename T, typename C>
845 void GrRedBlackTree<T,C>::validate() const {
847 SkASSERT(NULL == fRoot->fParent);
848 SkASSERT(NULL != fFirst);
849 SkASSERT(NULL != fLast);
851 SkASSERT(kBlack_Color == fRoot->fColor);
853 SkASSERT(fFirst == fRoot);
854 SkASSERT(fLast == fRoot);
855 SkASSERT(0 == fRoot->fChildren[kLeft_Child]);
856 SkASSERT(0 == fRoot->fChildren[kRight_Child]);
859 SkASSERT(NULL == fRoot);
860 SkASSERT(NULL == fFirst);
861 SkASSERT(NULL == fLast);
865 int count = checkNode(fRoot, &bh);
866 SkASSERT(count == fCount);
870 template <typename T, typename C>
871 int GrRedBlackTree<T,C>::checkNode(Node* n, int* bh) const {
873 SkASSERT(validateChildRelations(n, false));
874 if (kBlack_Color == n->fColor) {
877 SkASSERT(!fComp(n->fItem, fFirst->fItem));
878 SkASSERT(!fComp(fLast->fItem, n->fItem));
881 int cl = checkNode(n->fChildren[kLeft_Child], &leftBh);
882 int cr = checkNode(n->fChildren[kRight_Child], &rightBh);
883 SkASSERT(leftBh == rightBh);
890 template <typename T, typename C>
891 bool GrRedBlackTree<T,C>::validateChildRelations(const Node* n,
892 bool allowRedRed) const {
894 if (NULL != n->fChildren[kLeft_Child] ||
895 NULL != n->fChildren[kRight_Child]) {
896 if (n->fChildren[kLeft_Child] == n->fChildren[kRight_Child]) {
897 return validateChildRelationsFailed();
899 if (n->fChildren[kLeft_Child] == n->fParent &&
900 NULL != n->fParent) {
901 return validateChildRelationsFailed();
903 if (n->fChildren[kRight_Child] == n->fParent &&
904 NULL != n->fParent) {
905 return validateChildRelationsFailed();
907 if (NULL != n->fChildren[kLeft_Child]) {
909 kRed_Color == n->fChildren[kLeft_Child]->fColor &&
910 kRed_Color == n->fColor) {
911 return validateChildRelationsFailed();
913 if (n->fChildren[kLeft_Child]->fParent != n) {
914 return validateChildRelationsFailed();
916 if (!(fComp(n->fChildren[kLeft_Child]->fItem, n->fItem) ||
917 (!fComp(n->fChildren[kLeft_Child]->fItem, n->fItem) &&
918 !fComp(n->fItem, n->fChildren[kLeft_Child]->fItem)))) {
919 return validateChildRelationsFailed();
922 if (NULL != n->fChildren[kRight_Child]) {
924 kRed_Color == n->fChildren[kRight_Child]->fColor &&
925 kRed_Color == n->fColor) {
926 return validateChildRelationsFailed();
928 if (n->fChildren[kRight_Child]->fParent != n) {
929 return validateChildRelationsFailed();
931 if (!(fComp(n->fItem, n->fChildren[kRight_Child]->fItem) ||
932 (!fComp(n->fChildren[kRight_Child]->fItem, n->fItem) &&
933 !fComp(n->fItem, n->fChildren[kRight_Child]->fItem)))) {
934 return validateChildRelationsFailed();