1 /* Copyright (C) 1995-1997, 2000, 2006-2007, 2009-2020 Free Software
3 Contributed by Bernd Schmidt <crux@Pool.Informatik.RWTH-Aachen.DE>, 1997.
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.
8 This program is free software: you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 3 of the License, or any
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 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <https://www.gnu.org/licenses/>. */
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
29 Totally public domain. */
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
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
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.
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
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.
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. */
76 /* Tree rotations look like this:
85 In this case, A has been rotated left. This preserves the ordering of the
88 /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
89 optimizes away the rootp == NULL tests below. */
90 #define _GL_ARG_NONNULL(params)
103 typedef int (*__compar_fn_t
) (const void *, const void *);
104 typedef void (*__action_fn_t
) (const void *, VISIT
, int);
107 # define __tsearch tsearch
108 # define __tfind tfind
109 # define __tdelete tdelete
110 # define __twalk twalk
113 #ifndef internal_function
114 /* Inside GNU libc we mark some function in a special way. In other
115 environments simply ignore the marking. */
116 # define internal_function
119 typedef struct node_t
121 /* Callers expect this to be the first element in the structure - do not
125 struct node_t
*right
;
128 typedef const struct node_t
*const_node
;
134 /* Routines to check tree invariants. */
138 #define CHECK_TREE(a) check_tree(a)
141 check_tree_recurse (node p
, int d_sofar
, int d_total
)
145 assert (d_sofar
== d_total
);
149 check_tree_recurse (p
->left
, d_sofar
+ (p
->left
&& !p
->left
->red
), d_total
);
150 check_tree_recurse (p
->right
, d_sofar
+ (p
->right
&& !p
->right
->red
), d_total
);
152 assert (!(p
->left
->red
&& p
->red
));
154 assert (!(p
->right
->red
&& p
->red
));
158 check_tree (node root
)
165 for (p
= root
->left
; p
; p
= p
->left
)
167 check_tree_recurse (root
, 0, cnt
);
173 #define CHECK_TREE(a)
177 #if GNULIB_defined_tsearch
179 /* Possibly "split" a node with two red successors, and/or fix up two red
180 edges in a row. ROOTP is a pointer to the lowest node we visited, PARENTP
181 and GPARENTP pointers to its parent/grandparent. P_R and GP_R contain the
182 comparison values that determined which way was taken in the tree to reach
183 ROOTP. MODE is 1 if we need not do the split, but must check for two red
184 edges between GPARENTP and ROOTP. */
186 maybe_split_for_insert (node
*rootp
, node
*parentp
, node
*gparentp
,
187 int p_r
, int gp_r
, int mode
)
191 rp
= &(*rootp
)->right
;
192 lp
= &(*rootp
)->left
;
194 /* See if we have to split this node (both successors red). */
196 || ((*rp
) != NULL
&& (*lp
) != NULL
&& (*rp
)->red
&& (*lp
)->red
))
198 /* This node becomes red, its successors black. */
205 /* If the parent of this node is also red, we have to do
207 if (parentp
!= NULL
&& (*parentp
)->red
)
211 /* There are two main cases:
212 1. The edge types (left or right) of the two red edges differ.
213 2. Both red edges are of the same type.
214 There exist two symmetries of each case, so there is a total of
216 if ((p_r
> 0) != (gp_r
> 0))
218 /* Put the child at the top of the tree, with its parent
219 and grandparent as successors. */
225 /* Child is left of parent. */
233 /* Child is right of parent. */
243 *gparentp
= *parentp
;
244 /* Parent becomes the top of the tree, grandparent and
245 child are its successors. */
265 /* Find or insert datum into search tree.
266 KEY is the key to be located, ROOTP is the address of tree root,
267 COMPAR the ordering function. */
269 __tsearch (const void *key
, void **vrootp
, __compar_fn_t compar
)
272 node
*parentp
= NULL
, *gparentp
= NULL
;
273 node
*rootp
= (node
*) vrootp
;
275 int r
= 0, p_r
= 0, gp_r
= 0; /* No they might not, Mr Compiler. */
280 /* This saves some additional tests below. */
287 while (*nextp
!= NULL
)
290 r
= (*compar
) (key
, root
->key
);
294 maybe_split_for_insert (rootp
, parentp
, gparentp
, p_r
, gp_r
, 0);
295 /* If that did any rotations, parentp and gparentp are now garbage.
296 That doesn't matter, because the values they contain are never
297 used again in that case. */
299 nextp
= r
< 0 ? &root
->left
: &root
->right
;
311 q
= (struct node_t
*) malloc (sizeof (struct node_t
));
314 *nextp
= q
; /* link new node to old */
315 q
->key
= key
; /* initialize new node */
317 q
->left
= q
->right
= NULL
;
320 /* There may be two red edges in a row now, which we must avoid by
321 rotating the tree. */
322 maybe_split_for_insert (nextp
, rootp
, parentp
, r
, p_r
, 1);
328 weak_alias (__tsearch
, tsearch
)
332 /* Find datum in search tree.
333 KEY is the key to be located, ROOTP is the address of tree root,
334 COMPAR the ordering function. */
336 __tfind (const void *key
, void *const *vrootp
, __compar_fn_t compar
)
338 node
*rootp
= (node
*) vrootp
;
345 while (*rootp
!= NULL
)
350 r
= (*compar
) (key
, root
->key
);
354 rootp
= r
< 0 ? &root
->left
: &root
->right
;
359 weak_alias (__tfind
, tfind
)
363 /* Delete node with given key.
364 KEY is the key to be deleted, ROOTP is the address of the root of tree,
365 COMPAR the comparison function. */
367 __tdelete (const void *key
, void **vrootp
, __compar_fn_t compar
)
369 node p
, q
, r
, retval
;
371 node
*rootp
= (node
*) vrootp
;
372 node root
, unchained
;
373 /* Stack of nodes so we remember the parents without recursion. It's
374 _very_ unlikely that there are paths longer than 40 nodes. The tree
375 would need to have around 250.000 nodes. */
378 node
*nodestack
[100];
388 while ((cmp
= (*compar
) (key
, (*rootp
)->key
)) != 0)
393 nodestack
[sp
++] = rootp
;
402 /* This is bogus if the node to be deleted is the root... this routine
403 really should return an integer with 0 for success, -1 for failure
404 and errno = ESRCH or something. */
407 /* We don't unchain the node we want to delete. Instead, we overwrite
408 it with its successor and unchain the successor. If there is no
409 successor, we really unchain the node to be deleted. */
416 if (q
== NULL
|| r
== NULL
)
420 node
*parent
= rootp
, *up
= &root
->right
;
425 nodestack
[sp
++] = parent
;
427 if ((*up
)->left
== NULL
)
434 /* We know that either the left or right successor of UNCHAINED is NULL.
435 R becomes the other one, it is chained into the parent of UNCHAINED. */
438 r
= unchained
->right
;
443 q
= *nodestack
[sp
-1];
444 if (unchained
== q
->right
)
450 if (unchained
!= root
)
451 root
->key
= unchained
->key
;
454 /* Now we lost a black edge, which means that the number of black
455 edges on every path is no longer constant. We must balance the
457 /* NODESTACK now contains all parents of R. R is likely to be NULL
458 in the first iteration. */
459 /* NULL nodes are considered black throughout - this is necessary for
461 while (sp
> 0 && (r
== NULL
|| !r
->red
))
463 node
*pp
= nodestack
[sp
- 1];
465 /* Two symmetric cases. */
468 /* Q is R's brother, P is R's parent. The subtree with root
469 R has one black edge less than the subtree with root Q. */
473 /* If Q is red, we know that P is black. We rotate P left
474 so that Q becomes the top node in the tree, with P below
475 it. P is colored red, Q is colored black.
476 This action does not change the black edge count for any
477 leaf in the tree, but we will be able to recognize one
478 of the following situations, which all require that Q
486 /* Make sure pp is right if the case below tries to use
488 nodestack
[sp
++] = pp
= &q
->left
;
491 /* We know that Q can't be NULL here. We also know that Q is
493 if ((q
->left
== NULL
|| !q
->left
->red
)
494 && (q
->right
== NULL
|| !q
->right
->red
))
496 /* Q has two black successors. We can simply color Q red.
497 The whole subtree with root P is now missing one black
498 edge. Note that this action can temporarily make the
499 tree invalid (if P is red). But we will exit the loop
500 in that case and set P black, which both makes the tree
501 valid and also makes the black edge count come out
502 right. If P is black, we are at least one step closer
503 to the root and we'll try again the next iteration. */
509 /* Q is black, one of Q's successors is red. We can
510 repair the tree with one operation and will exit the
512 if (q
->right
== NULL
|| !q
->right
->red
)
514 /* The left one is red. We perform the same action as
515 in maybe_split_for_insert where two red edges are
516 adjacent but point in different directions:
517 Q's left successor (let's call it Q2) becomes the
518 top of the subtree we are looking at, its parent (Q)
519 and grandparent (P) become its successors. The former
520 successors of Q2 are placed below P and Q.
521 P becomes black, and Q2 gets the color that P had.
522 This changes the black edge count only for node R and
535 /* It's the right one. Rotate P left. P becomes black,
536 and Q gets the color that P had. Q's right successor
537 also becomes black. This changes the black edge
538 count only for node R and its successors. */
557 /* Comments: see above. */
566 nodestack
[sp
++] = pp
= &q
->right
;
569 if ((q
->right
== NULL
|| !q
->right
->red
)
570 && (q
->left
== NULL
|| !q
->left
->red
))
577 if (q
->left
== NULL
|| !q
->left
->red
)
611 weak_alias (__tdelete
, tdelete
)
614 #endif /* GNULIB_defined_tsearch */
617 #if GNULIB_defined_twalk
619 /* Walk the nodes of a tree.
620 ROOT is the root of the tree to be walked, ACTION the function to be
621 called at each node. LEVEL is the level of ROOT in the whole tree. */
624 trecurse (const void *vroot
, __action_fn_t action
, int level
)
626 const_node root
= (const_node
) vroot
;
628 if (root
->left
== NULL
&& root
->right
== NULL
)
629 (*action
) (root
, leaf
, level
);
632 (*action
) (root
, preorder
, level
);
633 if (root
->left
!= NULL
)
634 trecurse (root
->left
, action
, level
+ 1);
635 (*action
) (root
, postorder
, level
);
636 if (root
->right
!= NULL
)
637 trecurse (root
->right
, action
, level
+ 1);
638 (*action
) (root
, endorder
, level
);
643 /* Walk the nodes of a tree.
644 ROOT is the root of the tree to be walked, ACTION the function to be
645 called at each node. */
647 __twalk (const void *vroot
, __action_fn_t action
)
649 const_node root
= (const_node
) vroot
;
653 if (root
!= NULL
&& action
!= NULL
)
654 trecurse (root
, action
, 0);
657 weak_alias (__twalk
, twalk
)
660 #endif /* GNULIB_defined_twalk */
665 /* The standardized functions miss an important functionality: the
666 tree cannot be removed easily. We provide a function to do this. */
669 tdestroy_recurse (node root
, __free_fn_t freefct
)
671 if (root
->left
!= NULL
)
672 tdestroy_recurse (root
->left
, freefct
);
673 if (root
->right
!= NULL
)
674 tdestroy_recurse (root
->right
, freefct
);
675 (*freefct
) ((void *) root
->key
);
676 /* Free the node itself. */
681 __tdestroy (void *vroot
, __free_fn_t freefct
)
683 node root
= (node
) vroot
;
688 tdestroy_recurse (root
, freefct
);
690 weak_alias (__tdestroy
, tdestroy
)