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