2 * Copyright (c) 2004-2005, 2007,2009 Todd C. Miller <Todd.Miller@courtesan.com>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 * Adapted from the following code written by Emin Martinian:
19 * http://web.mit.edu/~emin/www/source_code/red_black_tree/index.html
21 * Copyright (c) 2001 Emin Martinian
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that neither the name of Emin
25 * Martinian nor the names of any contributors are be used to endorse or
26 * promote products derived from this software without specific prior
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
45 #include <sys/param.h>
55 #endif /* STDC_HEADERS */
61 __unused static const char rcsid[] = "$Sudo: redblack.c,v 1.12 2009/06/29 13:36:20 millert Exp $";
64 static void rbrepair __P((struct rbtree *, struct rbnode *));
65 static void rotate_left __P((struct rbtree *, struct rbnode *));
66 static void rotate_right __P((struct rbtree *, struct rbnode *));
67 static void _rbdestroy __P((struct rbtree *, struct rbnode *,
71 * Red-Black tree, see http://en.wikipedia.org/wiki/Red-black_tree
73 * A red-black tree is a binary search tree where each node has a color
74 * attribute, the value of which is either red or black. Essentially, it
75 * is just a convenient way to express a 2-3-4 binary search tree where
76 * the color indicates whether the node is part of a 3-node or a 4-node.
77 * In addition to the ordinary requirements imposed on binary search
78 * trees, we make the following additional requirements of any valid
80 * 1) Every node is either red or black.
81 * 2) The root is black.
82 * 3) All leaves are black.
83 * 4) Both children of each red node are black.
84 * 5) The paths from each leaf up to the root each contain the same
85 * number of black nodes.
89 * Create a red black tree struct using the specified compare routine.
90 * Allocates and returns the initialized (empty) tree.
94 int (*compar)__P((const void *, const void*));
98 tree = (struct rbtree *) emalloc(sizeof(*tree));
99 tree->compar = compar;
102 * We use a self-referencing sentinel node called nil to simplify the
103 * code by avoiding the need to check for NULL pointers.
105 tree->nil.left = tree->nil.right = tree->nil.parent = &tree->nil;
106 tree->nil.color = black;
107 tree->nil.data = NULL;
110 * Similarly, the fake root node keeps us from having to worry
111 * about splitting the root.
113 tree->root.left = tree->root.right = tree->root.parent = &tree->nil;
114 tree->root.color = black;
115 tree->root.data = NULL;
121 * Perform a left rotation starting at node.
124 rotate_left(tree, node)
128 struct rbnode *child;
131 node->right = child->left;
133 if (child->left != rbnil(tree))
134 child->left->parent = node;
135 child->parent = node->parent;
137 if (node == node->parent->left)
138 node->parent->left = child;
140 node->parent->right = child;
142 node->parent = child;
146 * Perform a right rotation starting at node.
149 rotate_right(tree, node)
153 struct rbnode *child;
156 node->left = child->right;
158 if (child->right != rbnil(tree))
159 child->right->parent = node;
160 child->parent = node->parent;
162 if (node == node->parent->left)
163 node->parent->left = child;
165 node->parent->right = child;
167 node->parent = child;
171 * Insert data pointer into a redblack tree.
172 * Returns a NULL pointer on success. If a node matching "data"
173 * already exists, a pointer to the existant node is returned.
180 struct rbnode *node = rbfirst(tree);
181 struct rbnode *parent = rbroot(tree);
184 /* Find correct insertion point. */
185 while (node != rbnil(tree)) {
187 if ((res = tree->compar(data, node->data)) == 0)
189 node = res < 0 ? node->left : node->right;
192 node = (struct rbnode *) emalloc(sizeof(*node));
194 node->left = node->right = rbnil(tree);
195 node->parent = parent;
196 if (parent == rbroot(tree) || tree->compar(data, parent->data) < 0)
199 parent->right = node;
203 * If the parent node is black we are all set, if it is red we have
204 * the following possible cases to deal with. We iterate through
205 * the rest of the tree to make sure none of the required properties
208 * 1) The uncle is red. We repaint both the parent and uncle black
209 * and repaint the grandparent node red.
211 * 2) The uncle is black and the new node is the right child of its
212 * parent, and the parent in turn is the left child of its parent.
213 * We do a left rotation to switch the roles of the parent and
214 * child, relying on further iterations to fixup the old parent.
216 * 3) The uncle is black and the new node is the left child of its
217 * parent, and the parent in turn is the left child of its parent.
218 * We switch the colors of the parent and grandparent and perform
219 * a right rotation around the grandparent. This makes the former
220 * parent the parent of the new node and the former grandparent.
222 * Note that because we use a sentinel for the root node we never
223 * need to worry about replacing the root.
225 while (node->parent->color == red) {
226 struct rbnode *uncle;
227 if (node->parent == node->parent->parent->left) {
228 uncle = node->parent->parent->right;
229 if (uncle->color == red) {
230 node->parent->color = black;
231 uncle->color = black;
232 node->parent->parent->color = red;
233 node = node->parent->parent;
234 } else /* if (uncle->color == black) */ {
235 if (node == node->parent->right) {
237 rotate_left(tree, node);
239 node->parent->color = black;
240 node->parent->parent->color = red;
241 rotate_right(tree, node->parent->parent);
243 } else { /* if (node->parent == node->parent->parent->right) */
244 uncle = node->parent->parent->left;
245 if (uncle->color == red) {
246 node->parent->color = black;
247 uncle->color = black;
248 node->parent->parent->color = red;
249 node = node->parent->parent;
250 } else /* if (uncle->color == black) */ {
251 if (node == node->parent->left) {
253 rotate_right(tree, node);
255 node->parent->color = black;
256 node->parent->parent->color = red;
257 rotate_left(tree, node->parent->parent);
261 rbfirst(tree)->color = black; /* first node is always black */
266 * Look for a node matching key in tree.
267 * Returns a pointer to the node if found, else NULL.
274 struct rbnode *node = rbfirst(tree);
277 while (node != rbnil(tree)) {
278 if ((res = tree->compar(key, node->data)) == 0)
280 node = res < 0 ? node->left : node->right;
286 * Call func() for each node, passing it the node data and a cookie;
287 * If func() returns non-zero for a node, the traversal stops and the
288 * error value is returned. Returns 0 on successful traversal.
291 rbapply_node(tree, node, func, cookie, order)
294 int (*func)__P((void *, void *));
296 enum rbtraversal order;
300 if (node != rbnil(tree)) {
301 if (order == preorder)
302 if ((error = func(node->data, cookie)) != 0)
304 if ((error = rbapply_node(tree, node->left, func, cookie, order)) != 0)
306 if (order == inorder)
307 if ((error = func(node->data, cookie)) != 0)
309 if ((error = rbapply_node(tree, node->right, func, cookie, order)) != 0)
311 if (order == postorder)
312 if ((error = func(node->data, cookie)) != 0)
319 * Returns the successor of node, or nil if there is none.
321 static struct rbnode *
322 rbsuccessor(tree, node)
328 if ((succ = node->right) != rbnil(tree)) {
329 while (succ->left != rbnil(tree))
332 /* No right child, move up until we find it or hit the root */
333 for (succ = node->parent; node == succ->right; succ = succ->parent)
335 if (succ == rbroot(tree))
342 * Recursive portion of rbdestroy().
345 _rbdestroy(tree, node, destroy)
348 void (*destroy)__P((void *));
350 if (node != rbnil(tree)) {
351 _rbdestroy(tree, node->left, destroy);
352 _rbdestroy(tree, node->right, destroy);
360 * Destroy the specified tree, calling the destructor destroy
361 * for each node and then freeing the tree itself.
364 rbdestroy(tree, destroy)
366 void (*destroy)__P((void *));
368 _rbdestroy(tree, rbfirst(tree), destroy);
373 * Delete node 'z' from the tree and return its data pointer.
375 void *rbdelete(tree, z)
379 struct rbnode *x, *y;
380 void *data = z->data;
382 if (z->left == rbnil(tree) || z->right == rbnil(tree))
385 y = rbsuccessor(tree, z);
386 x = (y->left == rbnil(tree)) ? y->right : y->left;
388 if ((x->parent = y->parent) == rbroot(tree)) {
391 if (y == y->parent->left)
394 y->parent->right = x;
396 if (y->color == black)
401 y->parent = z->parent;
403 z->left->parent = z->right->parent = y;
404 if (z == z->parent->left)
407 z->parent->right = y;
415 * Repair the tree after a node has been deleted by rotating and repainting
416 * colors to restore the 4 properties inherent in red-black trees.
423 struct rbnode *sibling;
425 while (node->color == black && node != rbroot(tree)) {
426 if (node == node->parent->left) {
427 sibling = node->parent->right;
428 if (sibling->color == red) {
429 sibling->color = black;
430 node->parent->color = red;
431 rotate_left(tree, node->parent);
432 sibling = node->parent->right;
434 if (sibling->right->color == black && sibling->left->color == black) {
435 sibling->color = red;
438 if (sibling->right->color == black) {
439 sibling->left->color = black;
440 sibling->color = red;
441 rotate_right(tree, sibling);
442 sibling = node->parent->right;
444 sibling->color = node->parent->color;
445 node->parent->color = black;
446 sibling->right->color = black;
447 rotate_left(tree, node->parent);
448 node = rbroot(tree); /* exit loop */
450 } else { /* if (node == node->parent->right) */
451 sibling = node->parent->left;
452 if (sibling->color == red) {
453 sibling->color = black;
454 node->parent->color = red;
455 rotate_right(tree, node->parent);
456 sibling = node->parent->left;
458 if (sibling->right->color == black && sibling->left->color == black) {
459 sibling->color = red;
462 if (sibling->left->color == black) {
463 sibling->right->color = black;
464 sibling->color = red;
465 rotate_left(tree, sibling);
466 sibling = node->parent->left;
468 sibling->color = node->parent->color;
469 node->parent->color = black;
470 sibling->left->color = black;
471 rotate_right(tree, node->parent);
472 node = rbroot(tree); /* exit loop */