1 /* Copyright (C) 1995-1997, 2000, 2006 Free Software Foundation, Inc.
2 Contributed by Bernd Schmidt <crux@Pool.Informatik.RWTH-Aachen.DE>, 1997.
3
4 NOTE: The canonical source of this file is maintained with the GNU C
5 Library. Bugs can be reported to bug-glibc@gnu.org.
6
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with this program. If not, see <https://www.gnu.org/licenses/>. */
19
20 /* Tree search for red/black trees.
21 The algorithm for adding nodes is taken from one of the many "Algorithms"
22 books by Robert Sedgewick, although the implementation differs.
23 The algorithm for deleting nodes can probably be found in a book named
24 "Introduction to Algorithms" by Cormen/Leiserson/Rivest. At least that's
25 the book that my professor took most algorithms from during the "Data
26 Structures" course...
27
28 Totally public domain. */
29
30 /* Red/black trees are binary trees in which the edges are colored either red
31 or black. They have the following properties:
32 1. The number of black edges on every path from the root to a leaf is
33 constant.
34 2. No two red edges are adjacent.
35 Therefore there is an upper bound on the length of every path, it's
36 O(log n) where n is the number of nodes in the tree. No path can be longer
37 than 1+2*P where P is the length of the shortest path in the tree.
38 Useful for the implementation:
39 3. If one of the children of a node is NULL, then the other one is red
40 (if it exists).
41
42 In the implementation, not the edges are colored, but the nodes. The color
43 interpreted as the color of the edge leading to this node. The color is
44 meaningless for the root node, but we color the root node black for
45 convenience. All added nodes are red initially.
46
47 Adding to a red/black tree is rather easy. The right place is searched
48 with a usual binary tree search. Additionally, whenever a node N is
49 reached that has two red successors, the successors are colored black and
50 the node itself colored red. This moves red edges up the tree where they
51 pose less of a problem once we get to really insert the new node. Changing
52 N's color to red may violate rule 2, however, so rotations may become
53 necessary to restore the invariants. Adding a new red leaf may violate
54 the same rule, so afterwards an additional check is run and the tree
55 possibly rotated.
56
57 Deleting is hairy. There are mainly two nodes involved: the node to be
58 deleted (n1), and another node that is to be unchained from the tree (n2).
59 If n1 has a successor (the node with a smallest key that is larger than
60 n1), then the successor becomes n2 and its contents are copied into n1,
61 otherwise n1 becomes n2.
62 Unchaining a node may violate rule 1: if n2 is black, one subtree is
63 missing one black edge afterwards. The algorithm must try to move this
64 error upwards towards the root, so that the subtree that does not have
65 enough black edges becomes the whole tree. Once that happens, the error
66 has disappeared. It may not be necessary to go all the way up, since it
67 is possible that rotations and recoloring can fix the error before that.
68
69 Although the deletion algorithm must walk upwards through the tree, we
70 do not store parent pointers in the nodes. Instead, delete allocates a
71 small array of parent pointers and fills it while descending the tree.
72 Since we know that the length of a path is O(log n), where n is the number
73 of nodes, this is likely to use less memory. */
74
75 /* Tree rotations look like this:
76 A C
77 / \ / \
78 B C A G
79 / \ / \ --> / \
80 D E F G B F
81 / \
82 D E
83
84 In this case, A has been rotated left. This preserves the ordering of the
85 binary tree. */
86
87 #include <config.h>
88
89 /* Specification. */
90 #ifdef IN_LIBINTL
91 # include "tsearch.h"
92 #else
93 # include <search.h>
94 #endif
95
96 #include <stdlib.h>
97
98 typedef int (*__compar_fn_t) (const void *, const void *);
99 typedef void (*__action_fn_t) (const void *, VISIT, int);
100
101 #ifndef weak_alias
102 # define __tsearch tsearch
103 # define __tfind tfind
104 # define __tdelete tdelete
105 # define __twalk twalk
106 #endif
107
108 #ifndef internal_function
109 /* Inside GNU libc we mark some function in a special way. In other
110 environments simply ignore the marking. */
111 # define internal_function
112 #endif
113
114 typedef struct node_t
115 {
116 /* Callers expect this to be the first element in the structure - do not
117 move! */
118 const void *key;
119 struct node_t *left;
120 struct node_t *right;
121 unsigned int red:1;
122 } *node;
123 typedef const struct node_t *const_node;
124
125 #undef DEBUGGING
126
127 #ifdef DEBUGGING
128
129 /* Routines to check tree invariants. */
130
131 #include <assert.h>
132
133 #define CHECK_TREE(a) check_tree(a)
134
135 static void
check_tree_recurse(node p,int d_sofar,int d_total)136 check_tree_recurse (node p, int d_sofar, int d_total)
137 {
138 if (p == NULL)
139 {
140 assert (d_sofar == d_total);
141 return;
142 }
143
144 check_tree_recurse (p->left, d_sofar + (p->left && !p->left->red), d_total);
145 check_tree_recurse (p->right, d_sofar + (p->right && !p->right->red), d_total);
146 if (p->left)
147 assert (!(p->left->red && p->red));
148 if (p->right)
149 assert (!(p->right->red && p->red));
150 }
151
152 static void
check_tree(node root)153 check_tree (node root)
154 {
155 int cnt = 0;
156 node p;
157 if (root == NULL)
158 return;
159 root->red = 0;
160 for(p = root->left; p; p = p->left)
161 cnt += !p->red;
162 check_tree_recurse (root, 0, cnt);
163 }
164
165
166 #else
167
168 #define CHECK_TREE(a)
169
170 #endif
171
172 /* Possibly "split" a node with two red successors, and/or fix up two red
173 edges in a row. ROOTP is a pointer to the lowest node we visited, PARENTP
174 and GPARENTP pointers to its parent/grandparent. P_R and GP_R contain the
175 comparison values that determined which way was taken in the tree to reach
176 ROOTP. MODE is 1 if we need not do the split, but must check for two red
177 edges between GPARENTP and ROOTP. */
178 static void
maybe_split_for_insert(node * rootp,node * parentp,node * gparentp,int p_r,int gp_r,int mode)179 maybe_split_for_insert (node *rootp, node *parentp, node *gparentp,
180 int p_r, int gp_r, int mode)
181 {
182 node root = *rootp;
183 node *rp, *lp;
184 rp = &(*rootp)->right;
185 lp = &(*rootp)->left;
186
187 /* See if we have to split this node (both successors red). */
188 if (mode == 1
189 || ((*rp) != NULL && (*lp) != NULL && (*rp)->red && (*lp)->red))
190 {
191 /* This node becomes red, its successors black. */
192 root->red = 1;
193 if (*rp)
194 (*rp)->red = 0;
195 if (*lp)
196 (*lp)->red = 0;
197
198 /* If the parent of this node is also red, we have to do
199 rotations. */
200 if (parentp != NULL && (*parentp)->red)
201 {
202 node gp = *gparentp;
203 node p = *parentp;
204 /* There are two main cases:
205 1. The edge types (left or right) of the two red edges differ.
206 2. Both red edges are of the same type.
207 There exist two symmetries of each case, so there is a total of
208 4 cases. */
209 if ((p_r > 0) != (gp_r > 0))
210 {
211 /* Put the child at the top of the tree, with its parent
212 and grandparent as successors. */
213 p->red = 1;
214 gp->red = 1;
215 root->red = 0;
216 if (p_r < 0)
217 {
218 /* Child is left of parent. */
219 p->left = *rp;
220 *rp = p;
221 gp->right = *lp;
222 *lp = gp;
223 }
224 else
225 {
226 /* Child is right of parent. */
227 p->right = *lp;
228 *lp = p;
229 gp->left = *rp;
230 *rp = gp;
231 }
232 *gparentp = root;
233 }
234 else
235 {
236 *gparentp = *parentp;
237 /* Parent becomes the top of the tree, grandparent and
238 child are its successors. */
239 p->red = 0;
240 gp->red = 1;
241 if (p_r < 0)
242 {
243 /* Left edges. */
244 gp->left = p->right;
245 p->right = gp;
246 }
247 else
248 {
249 /* Right edges. */
250 gp->right = p->left;
251 p->left = gp;
252 }
253 }
254 }
255 }
256 }
257
258 /* Find or insert datum into search tree.
259 KEY is the key to be located, ROOTP is the address of tree root,
260 COMPAR the ordering function. */
261 void *
__tsearch(const void * key,void ** vrootp,__compar_fn_t compar)262 __tsearch (const void *key, void **vrootp, __compar_fn_t compar)
263 {
264 node q;
265 node *parentp = NULL, *gparentp = NULL;
266 node *rootp = (node *) vrootp;
267 node *nextp;
268 int r = 0, p_r = 0, gp_r = 0; /* No they might not, Mr Compiler. */
269
270 if (rootp == NULL)
271 return NULL;
272
273 /* This saves some additional tests below. */
274 if (*rootp != NULL)
275 (*rootp)->red = 0;
276
277 CHECK_TREE (*rootp);
278
279 nextp = rootp;
280 while (*nextp != NULL)
281 {
282 node root = *rootp;
283 r = (*compar) (key, root->key);
284 if (r == 0)
285 return root;
286
287 maybe_split_for_insert (rootp, parentp, gparentp, p_r, gp_r, 0);
288 /* If that did any rotations, parentp and gparentp are now garbage.
289 That doesn't matter, because the values they contain are never
290 used again in that case. */
291
292 nextp = r < 0 ? &root->left : &root->right;
293 if (*nextp == NULL)
294 break;
295
296 gparentp = parentp;
297 parentp = rootp;
298 rootp = nextp;
299
300 gp_r = p_r;
301 p_r = r;
302 }
303
304 q = (struct node_t *) malloc (sizeof (struct node_t));
305 if (q != NULL)
306 {
307 *nextp = q; /* link new node to old */
308 q->key = key; /* initialize new node */
309 q->red = 1;
310 q->left = q->right = NULL;
311
312 if (nextp != rootp)
313 /* There may be two red edges in a row now, which we must avoid by
314 rotating the tree. */
315 maybe_split_for_insert (nextp, rootp, parentp, r, p_r, 1);
316 }
317
318 return q;
319 }
320 #ifdef weak_alias
321 weak_alias (__tsearch, tsearch)
322 #endif
323
324
325 /* Find datum in search tree.
326 KEY is the key to be located, ROOTP is the address of tree root,
327 COMPAR the ordering function. */
328 void *
329 __tfind (key, vrootp, compar)
330 const void *key;
331 void *const *vrootp;
332 __compar_fn_t compar;
333 {
334 node *rootp = (node *) vrootp;
335
336 if (rootp == NULL)
337 return NULL;
338
339 CHECK_TREE (*rootp);
340
341 while (*rootp != NULL)
342 {
343 node root = *rootp;
344 int r;
345
346 r = (*compar) (key, root->key);
347 if (r == 0)
348 return root;
349
350 rootp = r < 0 ? &root->left : &root->right;
351 }
352 return NULL;
353 }
354 #ifdef weak_alias
weak_alias(__tfind,tfind)355 weak_alias (__tfind, tfind)
356 #endif
357
358
359 /* Delete node with given key.
360 KEY is the key to be deleted, ROOTP is the address of the root of tree,
361 COMPAR the comparison function. */
362 void *
363 __tdelete (const void *key, void **vrootp, __compar_fn_t compar)
364 {
365 node p, q, r, retval;
366 int cmp;
367 node *rootp = (node *) vrootp;
368 node root, unchained;
369 /* Stack of nodes so we remember the parents without recursion. It's
370 _very_ unlikely that there are paths longer than 40 nodes. The tree
371 would need to have around 250.000 nodes. */
372 int stacksize = 100;
373 int sp = 0;
374 node *nodestack[100];
375
376 if (rootp == NULL)
377 return NULL;
378 p = *rootp;
379 if (p == NULL)
380 return NULL;
381
382 CHECK_TREE (p);
383
384 while ((cmp = (*compar) (key, (*rootp)->key)) != 0)
385 {
386 if (sp == stacksize)
387 abort ();
388
389 nodestack[sp++] = rootp;
390 p = *rootp;
391 rootp = ((cmp < 0)
392 ? &(*rootp)->left
393 : &(*rootp)->right);
394 if (*rootp == NULL)
395 return NULL;
396 }
397
398 /* This is bogus if the node to be deleted is the root... this routine
399 really should return an integer with 0 for success, -1 for failure
400 and errno = ESRCH or something. */
401 retval = p;
402
403 /* We don't unchain the node we want to delete. Instead, we overwrite
404 it with its successor and unchain the successor. If there is no
405 successor, we really unchain the node to be deleted. */
406
407 root = *rootp;
408
409 r = root->right;
410 q = root->left;
411
412 if (q == NULL || r == NULL)
413 unchained = root;
414 else
415 {
416 node *parent = rootp, *up = &root->right;
417 for (;;)
418 {
419 if (sp == stacksize)
420 abort ();
421 nodestack[sp++] = parent;
422 parent = up;
423 if ((*up)->left == NULL)
424 break;
425 up = &(*up)->left;
426 }
427 unchained = *up;
428 }
429
430 /* We know that either the left or right successor of UNCHAINED is NULL.
431 R becomes the other one, it is chained into the parent of UNCHAINED. */
432 r = unchained->left;
433 if (r == NULL)
434 r = unchained->right;
435 if (sp == 0)
436 *rootp = r;
437 else
438 {
439 q = *nodestack[sp-1];
440 if (unchained == q->right)
441 q->right = r;
442 else
443 q->left = r;
444 }
445
446 if (unchained != root)
447 root->key = unchained->key;
448 if (!unchained->red)
449 {
450 /* Now we lost a black edge, which means that the number of black
451 edges on every path is no longer constant. We must balance the
452 tree. */
453 /* NODESTACK now contains all parents of R. R is likely to be NULL
454 in the first iteration. */
455 /* NULL nodes are considered black throughout - this is necessary for
456 correctness. */
457 while (sp > 0 && (r == NULL || !r->red))
458 {
459 node *pp = nodestack[sp - 1];
460 p = *pp;
461 /* Two symmetric cases. */
462 if (r == p->left)
463 {
464 /* Q is R's brother, P is R's parent. The subtree with root
465 R has one black edge less than the subtree with root Q. */
466 q = p->right;
467 if (q->red)
468 {
469 /* If Q is red, we know that P is black. We rotate P left
470 so that Q becomes the top node in the tree, with P below
471 it. P is colored red, Q is colored black.
472 This action does not change the black edge count for any
473 leaf in the tree, but we will be able to recognize one
474 of the following situations, which all require that Q
475 is black. */
476 q->red = 0;
477 p->red = 1;
478 /* Left rotate p. */
479 p->right = q->left;
480 q->left = p;
481 *pp = q;
482 /* Make sure pp is right if the case below tries to use
483 it. */
484 nodestack[sp++] = pp = &q->left;
485 q = p->right;
486 }
487 /* We know that Q can't be NULL here. We also know that Q is
488 black. */
489 if ((q->left == NULL || !q->left->red)
490 && (q->right == NULL || !q->right->red))
491 {
492 /* Q has two black successors. We can simply color Q red.
493 The whole subtree with root P is now missing one black
494 edge. Note that this action can temporarily make the
495 tree invalid (if P is red). But we will exit the loop
496 in that case and set P black, which both makes the tree
497 valid and also makes the black edge count come out
498 right. If P is black, we are at least one step closer
499 to the root and we'll try again the next iteration. */
500 q->red = 1;
501 r = p;
502 }
503 else
504 {
505 /* Q is black, one of Q's successors is red. We can
506 repair the tree with one operation and will exit the
507 loop afterwards. */
508 if (q->right == NULL || !q->right->red)
509 {
510 /* The left one is red. We perform the same action as
511 in maybe_split_for_insert where two red edges are
512 adjacent but point in different directions:
513 Q's left successor (let's call it Q2) becomes the
514 top of the subtree we are looking at, its parent (Q)
515 and grandparent (P) become its successors. The former
516 successors of Q2 are placed below P and Q.
517 P becomes black, and Q2 gets the color that P had.
518 This changes the black edge count only for node R and
519 its successors. */
520 node q2 = q->left;
521 q2->red = p->red;
522 p->right = q2->left;
523 q->left = q2->right;
524 q2->right = q;
525 q2->left = p;
526 *pp = q2;
527 p->red = 0;
528 }
529 else
530 {
531 /* It's the right one. Rotate P left. P becomes black,
532 and Q gets the color that P had. Q's right successor
533 also becomes black. This changes the black edge
534 count only for node R and its successors. */
535 q->red = p->red;
536 p->red = 0;
537
538 q->right->red = 0;
539
540 /* left rotate p */
541 p->right = q->left;
542 q->left = p;
543 *pp = q;
544 }
545
546 /* We're done. */
547 sp = 1;
548 r = NULL;
549 }
550 }
551 else
552 {
553 /* Comments: see above. */
554 q = p->left;
555 if (q->red)
556 {
557 q->red = 0;
558 p->red = 1;
559 p->left = q->right;
560 q->right = p;
561 *pp = q;
562 nodestack[sp++] = pp = &q->right;
563 q = p->left;
564 }
565 if ((q->right == NULL || !q->right->red)
566 && (q->left == NULL || !q->left->red))
567 {
568 q->red = 1;
569 r = p;
570 }
571 else
572 {
573 if (q->left == NULL || !q->left->red)
574 {
575 node q2 = q->right;
576 q2->red = p->red;
577 p->left = q2->right;
578 q->right = q2->left;
579 q2->left = q;
580 q2->right = p;
581 *pp = q2;
582 p->red = 0;
583 }
584 else
585 {
586 q->red = p->red;
587 p->red = 0;
588 q->left->red = 0;
589 p->left = q->right;
590 q->right = p;
591 *pp = q;
592 }
593 sp = 1;
594 r = NULL;
595 }
596 }
597 --sp;
598 }
599 if (r != NULL)
600 r->red = 0;
601 }
602
603 free (unchained);
604 return retval;
605 }
606 #ifdef weak_alias
weak_alias(__tdelete,tdelete)607 weak_alias (__tdelete, tdelete)
608 #endif
609
610
611 /* Walk the nodes of a tree.
612 ROOT is the root of the tree to be walked, ACTION the function to be
613 called at each node. LEVEL is the level of ROOT in the whole tree. */
614 static void
615 internal_function
616 trecurse (const void *vroot, __action_fn_t action, int level)
617 {
618 const_node root = (const_node) vroot;
619
620 if (root->left == NULL && root->right == NULL)
621 (*action) (root, leaf, level);
622 else
623 {
624 (*action) (root, preorder, level);
625 if (root->left != NULL)
626 trecurse (root->left, action, level + 1);
627 (*action) (root, postorder, level);
628 if (root->right != NULL)
629 trecurse (root->right, action, level + 1);
630 (*action) (root, endorder, level);
631 }
632 }
633
634
635 /* Walk the nodes of a tree.
636 ROOT is the root of the tree to be walked, ACTION the function to be
637 called at each node. */
638 void
__twalk(const void * vroot,__action_fn_t action)639 __twalk (const void *vroot, __action_fn_t action)
640 {
641 const_node root = (const_node) vroot;
642
643 CHECK_TREE (root);
644
645 if (root != NULL && action != NULL)
646 trecurse (root, action, 0);
647 }
648 #ifdef weak_alias
weak_alias(__twalk,twalk)649 weak_alias (__twalk, twalk)
650 #endif
651
652
653 #ifdef _LIBC
654
655 /* The standardized functions miss an important functionality: the
656 tree cannot be removed easily. We provide a function to do this. */
657 static void
658 internal_function
659 tdestroy_recurse (node root, __free_fn_t freefct)
660 {
661 if (root->left != NULL)
662 tdestroy_recurse (root->left, freefct);
663 if (root->right != NULL)
664 tdestroy_recurse (root->right, freefct);
665 (*freefct) ((void *) root->key);
666 /* Free the node itself. */
667 free (root);
668 }
669
670 void
__tdestroy(void * vroot,__free_fn_t freefct)671 __tdestroy (void *vroot, __free_fn_t freefct)
672 {
673 node root = (node) vroot;
674
675 CHECK_TREE (root);
676
677 if (root != NULL)
678 tdestroy_recurse (root, freefct);
679 }
680 weak_alias (__tdestroy, tdestroy)
681
682 #endif /* _LIBC */
683