2 * Copyright (C) 2010 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 // A red-black tree, which is a form of a balanced binary tree. It
27 // supports efficient insertion, deletion and queries of comparable
28 // elements. The same element may be inserted multiple times. The
29 // algorithmic complexity of common operations is:
31 // Insertion: O(lg(n))
35 // The data type T that is stored in this red-black tree must be only
36 // Plain Old Data (POD), or bottom out into POD. It must _not_ rely on
37 // having its destructor called. This implementation internally
38 // allocates storage in large chunks and does not call the destructor
41 // Type T must supply a default constructor, a copy constructor, and
42 // the "<" and "==" operators.
44 // In debug mode, printing of the data contained in the tree is
45 // enabled. This requires the template specialization to be available:
47 // template<> struct WebCore::ValueToString<T> {
48 // static String string(const T& t);
51 // Note that when complex types are stored in this red/black tree, it
52 // is possible that single invocations of the "<" and "==" operators
53 // will be insufficient to describe the ordering of elements in the
54 // tree during queries. As a concrete example, consider the case where
55 // intervals are stored in the tree sorted by low endpoint. The "<"
56 // operator on the Interval class only compares the low endpoint, but
57 // the "==" operator takes into account the high endpoint as well.
58 // This makes the necessary logic for querying and deletion somewhat
59 // more complex. In order to properly handle such situations, the
60 // property "needsFullOrderingComparisons" must be set to true on
63 // This red-black tree is designed to be _augmented_; subclasses can
64 // add additional and summary information to each node to efficiently
65 // store and index more complex data structures. A concrete example is
66 // the IntervalTree, which extends each node with a summary statistic
67 // to efficiently store one-dimensional intervals.
69 // The design of this red-black tree comes from Cormen, Leiserson,
70 // and Rivest, _Introduction to Algorithms_, MIT Press, 1990.
72 #ifndef PODRedBlackTree_h
73 #define PODRedBlackTree_h
76 #include <wtf/Assertions.h>
77 #include <wtf/Noncopyable.h>
78 #include <wtf/RefPtr.h>
81 #include <wtf/text/CString.h>
82 #include <wtf/text/StringBuilder.h>
83 #include <wtf/text/WTFString.h>
94 class PODRedBlackTree {
96 // Visitor interface for walking all of the tree's elements.
99 virtual void visit(const T& data) = 0;
101 virtual ~Visitor() { }
104 // Constructs a new red-black tree, allocating temporary objects
105 // from a newly constructed PODArena.
107 : m_arena(PODArena::create())
109 , m_needsFullOrderingComparisons(false)
111 , m_verboseDebugging(false)
116 // Constructs a new red-black tree, allocating temporary objects
117 // from the given PODArena.
118 explicit PODRedBlackTree(PassRefPtr<PODArena> arena)
121 , m_needsFullOrderingComparisons(false)
123 , m_verboseDebugging(false)
128 virtual ~PODRedBlackTree() { }
130 void add(const T& data)
132 Node* node = m_arena->allocateObject<Node, T>(data);
136 // Returns true if the datum was found in the tree.
137 bool remove(const T& data)
139 Node* node = treeSearch(data);
147 bool contains(const T& data) const { return treeSearch(data); }
149 void visitInorder(Visitor* visitor) const
153 visitInorderImpl(m_root, visitor);
159 visitInorder(&counter);
160 return counter.count();
163 // See the class documentation for an explanation of this property.
164 void setNeedsFullOrderingComparisons(bool needsFullOrderingComparisons)
166 m_needsFullOrderingComparisons = needsFullOrderingComparisons;
169 virtual bool checkInvariants() const
172 return checkInvariantsFromNode(m_root, &blackCount);
176 // Dumps the tree's contents to the logging info stream for
177 // debugging purposes.
180 dumpFromNode(m_root, 0);
183 // Turns on or off verbose debugging of the tree, causing many
184 // messages to be logged during insertion and other operations in
186 void setVerboseDebugging(bool verboseDebugging)
188 m_verboseDebugging = verboseDebugging;
198 // The base Node class which is stored in the tree. Nodes are only
199 // an internal concept; users of the tree deal only with the data
202 WTF_MAKE_NONCOPYABLE(Node);
204 // Constructor. Newly-created nodes are colored red.
205 explicit Node(const T& data)
216 Color color() const { return m_color; }
217 void setColor(Color color) { m_color = color; }
219 // Fetches the user data.
220 T& data() { return m_data; }
222 // Copies all user-level fields from the source node, but not
223 // internal fields. For example, the base implementation of this
224 // method copies the "m_data" field, but not the child or parent
225 // fields. Any augmentation information also does not need to be
226 // copied, as it will be recomputed. Subclasses must call the
227 // superclass implementation.
228 virtual void copyFrom(Node* src) { m_data = src->data(); }
230 Node* left() const { return m_left; }
231 void setLeft(Node* node) { m_left = node; }
233 Node* right() const { return m_right; }
234 void setRight(Node* node) { m_right = node; }
236 Node* parent() const { return m_parent; }
237 void setParent(Node* node) { m_parent = node; }
247 // Returns the root of the tree, which is needed by some subclasses.
248 Node* root() const { return m_root; }
251 // This virtual method is the hook that subclasses should use when
252 // augmenting the red-black tree with additional per-node summary
253 // information. For example, in the case of an interval tree, this
254 // is used to compute the maximum endpoint of the subtree below the
255 // given node based on the values in the left and right children. It
256 // is guaranteed that this will be called in the correct order to
257 // properly update such summary information based only on the values
258 // in the left and right children. This method should return true if
259 // the node's summary information changed.
260 virtual bool updateNode(Node*) { return false; }
262 //----------------------------------------------------------------------
263 // Generic binary search tree operations
266 // Searches the tree for the given datum.
267 Node* treeSearch(const T& data) const
269 if (m_needsFullOrderingComparisons)
270 return treeSearchFullComparisons(m_root, data);
272 return treeSearchNormal(m_root, data);
275 // Searches the tree using the normal comparison operations,
276 // suitable for simple data types such as numbers.
277 Node* treeSearchNormal(Node* current, const T& data) const
280 if (current->data() == data)
282 if (data < current->data())
283 current = current->left();
285 current = current->right();
290 // Searches the tree using multiple comparison operations, required
291 // for data types with more complex behavior such as intervals.
292 Node* treeSearchFullComparisons(Node* current, const T& data) const
296 if (data < current->data())
297 return treeSearchFullComparisons(current->left(), data);
298 if (current->data() < data)
299 return treeSearchFullComparisons(current->right(), data);
300 if (data == current->data())
303 // We may need to traverse both the left and right subtrees.
304 Node* result = treeSearchFullComparisons(current->left(), data);
306 result = treeSearchFullComparisons(current->right(), data);
310 void treeInsert(Node* z)
316 if (z->data() < x->data())
325 if (z->data() < y->data())
332 // Finds the node following the given one in sequential ordering of
333 // their data, or null if none exists.
334 Node* treeSuccessor(Node* x)
337 return treeMinimum(x->right());
338 Node* y = x->parent();
339 while (y && x == y->right()) {
346 // Finds the minimum element in the sub-tree rooted at the given
348 Node* treeMinimum(Node* x)
355 // Helper for maintaining the augmented red-black tree.
356 void propagateUpdates(Node* start)
358 bool shouldContinue = true;
359 while (start && shouldContinue) {
360 shouldContinue = updateNode(start);
361 start = start->parent();
365 //----------------------------------------------------------------------
366 // Red-Black tree operations
369 // Left-rotates the subtree rooted at x.
370 // Returns the new root of the subtree (x's right child).
371 Node* leftRotate(Node* x)
374 Node* y = x->right();
376 // Turn y's left subtree into x's right subtree.
377 x->setRight(y->left());
379 y->left()->setParent(x);
381 // Link x's parent to y.
382 y->setParent(x->parent());
386 if (x == x->parent()->left())
387 x->parent()->setLeft(y);
389 x->parent()->setRight(y);
392 // Put x on y's left.
396 // Update nodes lowest to highest.
402 // Right-rotates the subtree rooted at y.
403 // Returns the new root of the subtree (y's left child).
404 Node* rightRotate(Node* y)
409 // Turn x's right subtree into y's left subtree.
410 y->setLeft(x->right());
412 x->right()->setParent(y);
414 // Link y's parent to x.
415 x->setParent(y->parent());
419 if (y == y->parent()->left())
420 y->parent()->setLeft(x);
422 y->parent()->setRight(x);
425 // Put y on x's right.
429 // Update nodes lowest to highest.
435 // Inserts the given node into the tree.
436 void insertNode(Node* x)
442 logIfVerbose(" PODRedBlackTree::InsertNode");
444 // The node from which to start propagating updates upwards.
445 Node* updateStart = x->parent();
447 while (x != m_root && x->parent()->color() == Red) {
448 if (x->parent() == x->parent()->parent()->left()) {
449 Node* y = x->parent()->parent()->right();
450 if (y && y->color() == Red) {
452 logIfVerbose(" Case 1/1");
453 x->parent()->setColor(Black);
455 x->parent()->parent()->setColor(Red);
456 updateNode(x->parent());
457 x = x->parent()->parent();
459 updateStart = x->parent();
461 if (x == x->parent()->right()) {
462 logIfVerbose(" Case 1/2");
468 logIfVerbose(" Case 1/3");
469 x->parent()->setColor(Black);
470 x->parent()->parent()->setColor(Red);
471 Node* newSubTreeRoot = rightRotate(x->parent()->parent());
472 updateStart = newSubTreeRoot->parent();
475 // Same as "then" clause with "right" and "left" exchanged.
476 Node* y = x->parent()->parent()->left();
477 if (y && y->color() == Red) {
479 logIfVerbose(" Case 2/1");
480 x->parent()->setColor(Black);
482 x->parent()->parent()->setColor(Red);
483 updateNode(x->parent());
484 x = x->parent()->parent();
486 updateStart = x->parent();
488 if (x == x->parent()->left()) {
490 logIfVerbose(" Case 2/2");
495 logIfVerbose(" Case 2/3");
496 x->parent()->setColor(Black);
497 x->parent()->parent()->setColor(Red);
498 Node* newSubTreeRoot = leftRotate(x->parent()->parent());
499 updateStart = newSubTreeRoot->parent();
504 propagateUpdates(updateStart);
506 m_root->setColor(Black);
509 // Restores the red-black property to the tree after splicing out
510 // a node. Note that x may be null, which is why xParent must be
512 void deleteFixup(Node* x, Node* xParent)
514 while (x != m_root && (!x || x->color() == Black)) {
515 if (x == xParent->left()) {
516 // Note: the text points out that w can not be null.
517 // The reason is not obvious from simply looking at
518 // the code; it comes about from the properties of the
520 Node* w = xParent->right();
521 ASSERT(w); // x's sibling should not be null.
522 if (w->color() == Red) {
525 xParent->setColor(Red);
527 w = xParent->right();
529 if ((!w->left() || w->left()->color() == Black)
530 && (!w->right() || w->right()->color() == Black)) {
534 xParent = x->parent();
536 if (!w->right() || w->right()->color() == Black) {
538 w->left()->setColor(Black);
541 w = xParent->right();
544 w->setColor(xParent->color());
545 xParent->setColor(Black);
547 w->right()->setColor(Black);
550 xParent = x->parent();
553 // Same as "then" clause with "right" and "left"
556 // Note: the text points out that w can not be null.
557 // The reason is not obvious from simply looking at
558 // the code; it comes about from the properties of the
560 Node* w = xParent->left();
561 ASSERT(w); // x's sibling should not be null.
562 if (w->color() == Red) {
565 xParent->setColor(Red);
566 rightRotate(xParent);
569 if ((!w->right() || w->right()->color() == Black)
570 && (!w->left() || w->left()->color() == Black)) {
574 xParent = x->parent();
576 if (!w->left() || w->left()->color() == Black) {
578 w->right()->setColor(Black);
584 w->setColor(xParent->color());
585 xParent->setColor(Black);
587 w->left()->setColor(Black);
588 rightRotate(xParent);
590 xParent = x->parent();
598 // Deletes the given node from the tree. Note that this
599 // particular node may not actually be removed from the tree;
600 // instead, another node might be removed and its contents
602 void deleteNode(Node* z)
604 // Y is the node to be unlinked from the tree.
606 if (!z->left() || !z->right())
609 y = treeSuccessor(z);
611 // Y is guaranteed to be non-null at this point.
618 // X is the child of y which might potentially replace y in
619 // the tree. X might be null at this point.
622 x->setParent(y->parent());
623 xParent = x->parent();
625 xParent = y->parent();
629 if (y == y->parent()->left())
630 y->parent()->setLeft(x);
632 y->parent()->setRight(x);
636 // This node has changed location in the tree and must be updated.
638 // The parent and its parents may now be out of date.
639 propagateUpdates(z->parent());
642 // If we haven't already updated starting from xParent, do so now.
643 if (xParent && xParent != y && xParent != z)
644 propagateUpdates(xParent);
645 if (y->color() == Black)
646 deleteFixup(x, xParent);
649 // Visits the subtree rooted at the given node in order.
650 void visitInorderImpl(Node* node, Visitor* visitor) const
653 visitInorderImpl(node->left(), visitor);
654 visitor->visit(node->data());
656 visitInorderImpl(node->right(), visitor);
659 //----------------------------------------------------------------------
660 // Helper class for size()
662 // A Visitor which simply counts the number of visited elements.
663 class Counter : public Visitor {
664 WTF_MAKE_NONCOPYABLE(Counter);
669 virtual void visit(const T&) { ++m_count; }
670 int count() const { return m_count; }
676 //----------------------------------------------------------------------
677 // Verification and debugging routines
680 // Returns in the "blackCount" parameter the number of black
681 // children along all paths to all leaves of the given node.
682 bool checkInvariantsFromNode(Node* node, int* blackCount) const
684 // Base case is a leaf node.
690 // Each node is either red or black.
691 if (!(node->color() == Red || node->color() == Black))
694 // Every leaf (or null) is black.
696 if (node->color() == Red) {
697 // Both of its children are black.
698 if (!((!node->left() || node->left()->color() == Black)))
700 if (!((!node->right() || node->right()->color() == Black)))
704 // Every simple path to a leaf node contains the same number of
706 int leftCount = 0, rightCount = 0;
707 bool leftValid = checkInvariantsFromNode(node->left(), &leftCount);
708 bool rightValid = checkInvariantsFromNode(node->right(), &rightCount);
709 if (!leftValid || !rightValid)
711 *blackCount = leftCount + (node->color() == Black ? 1 : 0);
712 return leftCount == rightCount;
716 void logIfVerbose(const char*) const { }
718 void logIfVerbose(const char* output) const
720 if (m_verboseDebugging)
721 LOG_ERROR("%s", output);
726 // Dumps the subtree rooted at the given node.
727 void dumpFromNode(Node* node, int indentation) const
729 StringBuilder builder;
730 for (int i = 0; i < indentation; i++)
735 builder.append(ValueToString<T>::string(node->data()));
736 builder.append((node->color() == Black) ? " (black)" : " (red)");
738 LOG_ERROR("%s", builder.toString().ascii().data());
740 dumpFromNode(node->left(), indentation + 2);
741 dumpFromNode(node->right(), indentation + 2);
746 //----------------------------------------------------------------------
749 RefPtr<PODArena> m_arena;
751 bool m_needsFullOrderingComparisons;
753 bool m_verboseDebugging;
757 } // namespace WebCore
759 #endif // PODRedBlackTree_h