2 * Copyright (c) 2004-2005, 2007 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.10 2008/11/22 15:01:25 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) The root is black.
81 * 2) All leaves are black.
82 * 3) Both children of each red node are black.
83 * 4) The paths from each leaf up to the root each contain the same
84 * number of black nodes.
88 * Create a red black tree struct using the specified compare routine.
89 * Allocates and returns the initialized (empty) tree.
93 int (*compar)__P((const void *, const void*));
97 tree = (struct rbtree *) emalloc(sizeof(*tree));
98 tree->compar = compar;
101 * We use a self-referencing sentinel node called nil to simplify the
102 * code by avoiding the need to check for NULL pointers.
104 tree->nil.left = tree->nil.right = tree->nil.parent = &tree->nil;
105 tree->nil.color = black;
106 tree->nil.data = NULL;
109 * Similarly, the fake root node keeps us from having to worry
110 * about splitting the root.
112 tree->root.left = tree->root.right = tree->root.parent = &tree->nil;
113 tree->root.color = black;
114 tree->root.data = NULL;
120 * Perform a left rotation starting at node.
123 rotate_left(tree, node)
127 struct rbnode *child;
130 node->right = child->left;
132 if (child->left != rbnil(tree))
133 child->left->parent = node;
134 child->parent = node->parent;
136 if (node == node->parent->left)
137 node->parent->left = child;
139 node->parent->right = child;
141 node->parent = child;
145 * Perform a right rotation starting at node.
148 rotate_right(tree, node)
152 struct rbnode *child;
155 node->left = child->right;
157 if (child->right != rbnil(tree))
158 child->right->parent = node;
159 child->parent = node->parent;
161 if (node == node->parent->left)
162 node->parent->left = child;
164 node->parent->right = child;
166 node->parent = child;
170 * Insert data pointer into a redblack tree.
171 * Returns a NULL pointer on success. If a node matching "data"
172 * already exists, a pointer to the existant node is returned.
179 struct rbnode *node = rbfirst(tree);
180 struct rbnode *parent = rbroot(tree);
183 /* Find correct insertion point. */
184 while (node != rbnil(tree)) {
186 if ((res = tree->compar(data, node->data)) == 0)
188 node = res < 0 ? node->left : node->right;
191 node = (struct rbnode *) emalloc(sizeof(*node));
193 node->left = node->right = rbnil(tree);
194 node->parent = parent;
195 if (parent == rbroot(tree) || tree->compar(data, parent->data) < 0)
198 parent->right = node;
202 * If the parent node is black we are all set, if it is red we have
203 * the following possible cases to deal with. We iterate through
204 * the rest of the tree to make sure none of the required properties
207 * 1) The uncle is red. We repaint both the parent and uncle black
208 * and repaint the grandparent node red.
210 * 2) The uncle is black and the new node is the right child of its
211 * parent, and the parent in turn is the left child of its parent.
212 * We do a left rotation to switch the roles of the parent and
213 * child, relying on further iterations to fixup the old parent.
215 * 3) The uncle is black and the new node is the left child of its
216 * parent, and the parent in turn is the left child of its parent.
217 * We switch the colors of the parent and grandparent and perform
218 * a right rotation around the grandparent. This makes the former
219 * parent the parent of the new node and the former grandparent.
221 * Note that because we use a sentinel for the root node we never
222 * need to worry about replacing the root.
224 while (node->parent->color == red) {
225 struct rbnode *uncle;
226 if (node->parent == node->parent->parent->left) {
227 uncle = node->parent->parent->right;
228 if (uncle->color == red) {
229 node->parent->color = black;
230 uncle->color = black;
231 node->parent->parent->color = red;
232 node = node->parent->parent;
233 } else /* if (uncle->color == black) */ {
234 if (node == node->parent->right) {
236 rotate_left(tree, node);
238 node->parent->color = black;
239 node->parent->parent->color = red;
240 rotate_right(tree, node->parent->parent);
242 } else { /* if (node->parent == node->parent->parent->right) */
243 uncle = node->parent->parent->left;
244 if (uncle->color == red) {
245 node->parent->color = black;
246 uncle->color = black;
247 node->parent->parent->color = red;
248 node = node->parent->parent;
249 } else /* if (uncle->color == black) */ {
250 if (node == node->parent->left) {
252 rotate_right(tree, node);
254 node->parent->color = black;
255 node->parent->parent->color = red;
256 rotate_left(tree, node->parent->parent);
260 rbfirst(tree)->color = black; /* first node is always black */
265 * Look for a node matching key in tree.
266 * Returns a pointer to the node if found, else NULL.
273 struct rbnode *node = rbfirst(tree);
276 while (node != rbnil(tree)) {
277 if ((res = tree->compar(key, node->data)) == 0)
279 node = res < 0 ? node->left : node->right;
285 * Call func() for each node, passing it the node data and a cookie;
286 * If func() returns non-zero for a node, the traversal stops and the
287 * error value is returned. Returns 0 on successful traversal.
290 rbapply_node(tree, node, func, cookie, order)
293 int (*func)__P((void *, void *));
295 enum rbtraversal order;
299 if (node != rbnil(tree)) {
300 if (order == preorder)
301 if ((error = func(node->data, cookie)) != 0)
303 if ((error = rbapply_node(tree, node->left, func, cookie, order)) != 0)
305 if (order == inorder)
306 if ((error = func(node->data, cookie)) != 0)
308 if ((error = rbapply_node(tree, node->right, func, cookie, order)) != 0)
310 if (order == postorder)
311 if ((error = func(node->data, cookie)) != 0)
318 * Returns the successor of node, or nil if there is none.
320 static struct rbnode *
321 rbsuccessor(tree, node)
327 if ((succ = node->right) != rbnil(tree)) {
328 while (succ->left != rbnil(tree))
331 /* No right child, move up until we find it or hit the root */
332 for (succ = node->parent; node == succ->right; succ = succ->parent)
334 if (succ == rbroot(tree))
341 * Recursive portion of rbdestroy().
344 _rbdestroy(tree, node, destroy)
347 void (*destroy)__P((void *));
349 if (node != rbnil(tree)) {
350 _rbdestroy(tree, node->left, destroy);
351 _rbdestroy(tree, node->right, destroy);
359 * Destroy the specified tree, calling the destructor destroy
360 * for each node and then freeing the tree itself.
363 rbdestroy(tree, destroy)
365 void (*destroy)__P((void *));
367 _rbdestroy(tree, rbfirst(tree), destroy);
372 * Delete node 'z' from the tree and return its data pointer.
374 void *rbdelete(tree, z)
378 struct rbnode *x, *y;
379 void *data = z->data;
381 if (z->left == rbnil(tree) || z->right == rbnil(tree))
384 y = rbsuccessor(tree, z);
385 x = (y->left == rbnil(tree)) ? y->right : y->left;
387 if ((x->parent = y->parent) == rbroot(tree)) {
390 if (y == y->parent->left)
393 y->parent->right = x;
395 if (y->color == black)
400 y->parent = z->parent;
402 z->left->parent = z->right->parent = y;
403 if (z == z->parent->left)
406 z->parent->right = y;
414 * Repair the tree after a node has been deleted by rotating and repainting
415 * colors to restore the 4 properties inherent in red-black trees.
422 struct rbnode *sibling;
424 while (node->color == black) {
425 if (node == node->parent->left) {
426 sibling = node->parent->right;
427 if (sibling->color == red) {
428 sibling->color = black;
429 node->parent->color = red;
430 rotate_left(tree, node->parent);
431 sibling = node->parent->right;
433 if (sibling->right->color == black && sibling->left->color == black) {
434 sibling->color = red;
437 if (sibling->right->color == black) {
438 sibling->left->color = black;
439 sibling->color = red;
440 rotate_right(tree, sibling);
441 sibling = node->parent->right;
443 sibling->color = node->parent->color;
444 node->parent->color = black;
445 sibling->right->color = black;
446 rotate_left(tree, node->parent);
449 } else { /* if (node == node->parent->right) */
450 sibling = node->parent->left;
451 if (sibling->color == red) {
452 sibling->color = black;
453 node->parent->color = red;
454 rotate_right(tree, node->parent);
455 sibling = node->parent->left;
457 if (sibling->right->color == black && sibling->left->color == black) {
458 sibling->color = red;
461 if (sibling->left->color == black) {
462 sibling->right->color = black;
463 sibling->color = red;
464 rotate_left(tree, sibling);
465 sibling = node->parent->left;
467 sibling->color = node->parent->color;
468 node->parent->color = black;
469 sibling->left->color = black;
470 rotate_right(tree, node->parent);