tsearch.c 21 KB

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