avltr.c
上传用户:shenzhenrh
上传日期:2013-05-12
资源大小:2904k
文件大小:32k
源码类别:

信息检索与抽取

开发平台:

Unix_Linux

  1. /* libavl - manipulates AVL trees.
  2.    Copyright (C) 1998, 1999 Free Software Foundation, Inc.
  3.    This program is free software; you can redistribute it and/or
  4.    modify it under the terms of the GNU General Public License as
  5.    published by the Free Software Foundation; either version 2 of the
  6.    License, or (at your option) any later version.
  7.    This program is distributed in the hope that it will be useful, but
  8.    WITHOUT ANY WARRANTY; without even the implied warranty of
  9.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  10.    General Public License for more details.
  11.    You should have received a copy of the GNU General Public License
  12.    along with this program; if not, write to the Free Software
  13.    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  14.    02111-1307, USA.
  15.    The author may be contacted at <pfaffben@pilot.msu.edu> on the
  16.    Internet, or as Ben Pfaff, 12167 Airport Rd, DeWitt MI 48820, USA
  17.    through more mundane means. */
  18. /* This is file avltr.c in libavl. */
  19. /* Modified by mgd@swarm.org 2000-09-10 to disable HAVE_CONFIG_H and PSPP code.
  20.    Force definition of HAVE_XMALLOC. */
  21. #if 0
  22. #if HAVE_CONFIG_H
  23. #include <config.h>
  24. #endif
  25. #endif
  26. #define HAVE_XMALLOC
  27. #if SELF_TEST 
  28. #include <limits.h>
  29. #include <time.h>
  30. #endif
  31. #include <stdio.h>
  32. #include <stddef.h>
  33. #include <stdlib.h>
  34. #include <assert.h>
  35. #include "avltr.h"
  36. /* Tag types. */
  37. #define PLUS +1
  38. #define MINUS -1
  39. #if !__GCC__ && !defined (inline)
  40. #define inline
  41. #endif
  42. void
  43. print_structure (avltr_tree *tree, avltr_node *node, int level);
  44. #if __GNUC__ >= 2
  45. #define unused __attribute__ ((unused))
  46. #else
  47. #define unused
  48. #endif
  49. #ifdef HAVE_XMALLOC
  50. void *xmalloc (size_t);
  51. void xfree (void *);
  52. #else /* !HAVE_XMALLOC */
  53. /* Allocates SIZE bytes of space using malloc().  Aborts if out of
  54.    memory. */
  55. static void *
  56. xmalloc (size_t size)
  57. {
  58.   void *vp;
  59.   if (size == 0)
  60.     return NULL;
  61.   vp = malloc (size);
  62.   assert (vp != NULL);
  63.   if (vp == NULL)
  64.     {
  65.       fprintf (stderr, "virtual memory exhaustedn");
  66.       exit (EXIT_FAILURE);
  67.     }
  68.   return vp;
  69. }
  70. #endif /* !HAVE_XMALLOC */
  71. /* Creates an AVL tree in arena OWNER (which can be NULL).  The arena
  72.    is owned by the caller, not by the AVL tree.  CMP is a order
  73.    function for the data to be stored in the tree.  PARAM is arbitrary
  74.    data that becomes an argument to the comparison function. */
  75. avltr_tree *
  76. avltr_create (avl_comparison_func cmp, void *param)
  77. {
  78.   avltr_tree *tree;
  79.   assert (cmp != NULL);
  80.   tree = xmalloc (sizeof (avltr_tree));
  81.   tree->root.link[0] = NULL;
  82.   tree->root.link[1] = &tree->root;
  83.   tree->root.rtag = PLUS;
  84.   tree->cmp = cmp;
  85.   tree->count = 0;
  86.   tree->param = param;
  87.   return tree;
  88. }
  89. /* Destroy tree TREE.  Function FREE_FUNC is called for every node in
  90.    the tree as it is destroyed.  
  91.    No effect if the tree has an arena owner and free_func is NULL.
  92.    The caller owns the arena and must destroy it itself.
  93.    Do not attempt to reuse the tree after it has been freed.  Create a
  94.    new one.  */
  95. void
  96. avltr_destroy (avltr_tree *tree, avl_node_func free_func)
  97. {
  98.   assert (tree != NULL);
  99.   
  100.   if (tree->root.link[0] != &tree->root)
  101.     {
  102.       /* Uses Knuth's Algorithm 2.3.1T as modified in exercise 13
  103.  (postorder traversal), further modified for right-threaded
  104.  trees. */
  105.       
  106.       /* T1. */
  107.       avltr_node *an[AVL_MAX_HEIGHT]; /* Stack A: nodes. */
  108.       char ab[AVL_MAX_HEIGHT]; /* Stack A: bits. */
  109.       int ap = 0; /* Stack A: height. */
  110.       avltr_node *p = tree->root.link[0];
  111.       for (;;)
  112. {
  113.   /* T2. */
  114.   while (p != NULL)
  115.     {
  116.       /* T3. */
  117.       ab[ap] = 0;
  118.       an[ap++] = p;
  119.       p = p->link[0];
  120.     }
  121.   /* T4. */
  122.   for (;;)
  123.     {
  124.       if (ap == 0)
  125. goto done;
  126.       p = an[--ap];
  127.       if (ab[ap] == 0)
  128. {
  129.   ab[ap++] = 1;
  130.   if (p->rtag == MINUS)
  131.     continue;
  132.   p = p->link[1];
  133.   break;
  134. }
  135.       
  136.       if (free_func)
  137. free_func (p->data, tree->param);
  138.       xfree (p);
  139.     }
  140. }
  141.     }
  142.  done:
  143.   xfree (tree);
  144. }
  145. /* avltr_destroy() with FREE_FUNC hardcoded as free(). */
  146. void
  147. avltr_free (avltr_tree *tree)
  148. {
  149.   avltr_destroy (tree, (avl_node_func) xfree);
  150. }
  151. /* Return the number of nodes in TREE. */
  152. int
  153. avltr_count (const avltr_tree *tree)
  154. {
  155.   assert (tree != NULL);
  156.   return tree->count;
  157. }
  158. /* Copy the contents of TREE to a new tree in arena OWNER.  If COPY is
  159.    non-NULL, then each data item is passed to function COPY, and the
  160.    return values are inserted into the new tree; otherwise, the items
  161.    are copied verbatim from the old tree to the new tree.  Returns the
  162.    new tree. */
  163. avltr_tree *
  164. avltr_copy (const avltr_tree *tree, avl_copy_func copy)
  165. {
  166.   /* Knuth's Algorithm 2.3.1C (copying a binary tree).  Additionally
  167.      uses Algorithm 2.3.1I (insertion into a threaded binary tree) and
  168.      Algorithm 2.3.1 exercise 17 (preorder successor in threaded
  169.      binary tree).  */
  170.   avltr_tree *new_tree;
  171.   const avltr_node *p;
  172.   avltr_node *q;
  173.   
  174.   assert (tree != NULL);
  175.   new_tree = avltr_create (tree->cmp, tree->param);
  176.   new_tree->count = tree->count;
  177.   p = &tree->root;
  178.   if (p->link[0] == p)
  179.     return new_tree;
  180.   q = &new_tree->root;
  181.   for (;;)
  182.     {
  183.       /* C4.  This is Algorithm 2.3.1 exercise 23 for insertion to the
  184.        left in a right-threaded binary tree. */
  185.       if (p->link[0] != NULL)
  186. {
  187.   avltr_node *r = xmalloc (sizeof (avltr_node));
  188.   q->link[0] = r;
  189.   r->link[0] = NULL;
  190.   r->link[1] = q;
  191.   r->rtag = MINUS;
  192. }
  193.       /* C5: Find preorder successors of P and Q.  This is Algorithm
  194.          2.3.1 exercise 17 but applies its actions to Q as well as
  195.          P. */
  196.       if (p->link[0] != NULL)
  197. {
  198.   p = p->link[0];
  199.   q = q->link[0];
  200. }
  201.       else
  202. {
  203.   while (p->rtag == MINUS)
  204.     {
  205.       p = p->link[1];
  206.       q = q->link[1];
  207.     }
  208.   p = p->link[1];
  209.   q = q->link[1];
  210. }
  211.       /* C6. */
  212.       if (p == &tree->root)
  213. {
  214.   assert (q == &new_tree->root);
  215.   return new_tree;
  216. }
  217.       
  218.       /* C2.  This is Algorithm 2.3.1 exercise 23 for insertion to the
  219.  right in a right-threaded binary tree. */
  220.       if (p->rtag == PLUS)
  221. {
  222.   avltr_node *r = xmalloc (sizeof (avltr_node));
  223.   r->link[1] = q->link[1];
  224.   r->rtag = q->rtag;
  225.   q->link[1] = r;
  226.   q->rtag = PLUS;
  227.   r->link[0] = NULL;
  228. }
  229.       /* C3. */
  230.       q->bal = p->bal;
  231.       if (copy == NULL)
  232. q->data = p->data;
  233.       else
  234. q->data = copy (p->data, tree->param);
  235.     }
  236. }
  237. /* Threads the unthreaded AVL tree TREE in-place, and returns TREE cast to
  238.    avltr_tree *. */
  239. avltr_tree *
  240. avltr_thread (struct avl_tree *_tree)
  241. {
  242.   /* Uses Knuth's Algorithm 2.3.1 exercise 30 (thread an unthreaded
  243.      tree, with Algorithm 2.3.1T (inorder traversal) for computing
  244.      Q$. */
  245.   avltr_tree *tree = (avltr_tree *) _tree;
  246.   /* Algorithm T's variables. */
  247.   avltr_node *an[AVL_MAX_HEIGHT]; /* Stack A: nodes. */
  248.   avltr_node **ap; /* Stack A: stack pointer. */
  249.   avltr_node *tp; /* P. */
  250.   /* Algorithm L's variables. */
  251.   avltr_node *p, *q;
  252.   assert (tree != NULL);
  253.   /* T1. */
  254.   ap = an;
  255.   tp = tree->root.link[0];
  256.   /* L1. */
  257.   q = &tree->root;
  258.   q->link[1] = q;
  259.   for (;;)
  260.     {
  261.       /* L2. */
  262.       {
  263. /* T2. */
  264. while (tp != NULL)
  265.   {
  266.     /* T3. */
  267.     *ap++ = tp;
  268.     tp = tp->link[0];
  269.   }
  270.       
  271. /* T4.  Modified to visit HEAD after fully traversing the
  272.            tree. */
  273. if (ap == an)
  274.   tp = &tree->root;
  275. else
  276.   tp = *--ap;
  277. /* T5: Visit P. */
  278. p = tp;
  279.       }
  280.       /* L3. */
  281.       if (q->link[1] == NULL)
  282. {
  283.   q->link[1] = p;
  284.   q->rtag = MINUS;
  285. }
  286.       else
  287. q->rtag = PLUS;
  288.   
  289.       /* L4. */
  290.       if (p == &tree->root)
  291. return tree;
  292.       q = p;
  293.       /* T5: Next. */
  294.       tp = tp->link[1];
  295.     }
  296. }
  297. /* Unthreads the threaded tree TREE in-place, and returns TREE cast to
  298.    avl_tree *. */
  299. struct avl_tree *
  300. avltr_unthread (avltr_tree *tree)
  301. {
  302.   /* Uses Knuth's Algorithm 2.3.1T as modified in exercise 13
  303.      (postorder traversal). */
  304.       
  305.   /* T1. */
  306.   avltr_node *an[AVL_MAX_HEIGHT]; /* Stack A: nodes. */
  307.   char ab[AVL_MAX_HEIGHT]; /* Stack A: bits. */
  308.   int ap = 0; /* Stack A: height. */
  309.   avltr_node *p;
  310.   assert (tree != NULL);
  311.   p = tree->root.link[0];
  312.   if (p != NULL)
  313.     for (;;)
  314.       {
  315. /* T2. */
  316. for (;;)
  317.   {
  318.     /* T3. */
  319.     ab[ap] = 0;
  320.     an[ap++] = p;
  321.     if (p->link[0] == NULL)
  322.       break;
  323.     p = p->link[0];
  324.   }
  325. /* T4. */
  326. for (;;)
  327.   {
  328.     if (ap == 0)
  329.       goto done;
  330.     p = an[--ap];
  331.     if (ab[ap] == 0)
  332.       {
  333. ab[ap++] = 1;
  334. if (p->rtag == MINUS)
  335.   continue;
  336. p = p->link[1];
  337. break;
  338.       }
  339.       
  340.     if (p->rtag == MINUS)
  341.       p->link[1] = NULL;
  342.   }
  343.       }
  344.   else
  345.     tree->root.link[0] = NULL;
  346.  done:
  347.   tree->root.link[1] = NULL;
  348.   return (struct avl_tree *) tree;
  349. }
  350. /* Walk tree TREE in inorder, calling WALK_FUNC at each node.  Passes
  351.    PARAM to WALK_FUNC.  */
  352. void
  353. avltr_walk (const avltr_tree *tree, avl_node_func walk_func, void *param)
  354. {
  355.   const avltr_node *p = &tree->root;
  356.   /* Uses Knuth's algorithm 2.3.1D (threaded inorder successor). */
  357.   assert (tree && walk_func);
  358.   
  359.   for (;;)
  360.     {
  361.       if (p->rtag == MINUS)
  362. p = p->link[1];
  363.       else
  364. {
  365.   p = p->link[1];
  366.   while (p->link[0] != NULL)
  367.     p = p->link[0];
  368. }
  369.       if (p == &tree->root)
  370. return;
  371.       walk_func (p->data, param);
  372.     }
  373. }
  374. /* Each call to this function for a given TREE and TRAV return the
  375.    next item in the tree in inorder.  Initialize the first element of
  376.    TRAV (init) to 0 before calling the first time.  Returns NULL when
  377.    out of elements.  */
  378. void *
  379. avltr_traverse (const avltr_tree *tree, avltr_traverser *trav)
  380. {
  381.   const avltr_node *p;
  382.   
  383.   assert (tree && trav);
  384.   if (trav->init == 0)
  385.     {
  386.       p = &tree->root;
  387.       trav->init = 1;
  388.     }
  389.   else
  390.     p = trav->p;
  391.   /* Knuth's Algorithm 2.3.1S (threaded inorder successor). */
  392.   if (p->rtag == MINUS)
  393.     p = p->link[1];
  394.   else
  395.     {
  396.       p = p->link[1];
  397.       while (p->link[0] != NULL)
  398. p = p->link[0];
  399.     }
  400.   if (p == &tree->root)
  401.     {
  402.       trav->init = 0;
  403.       return NULL;
  404.     }
  405.   else
  406.     {
  407.       trav->p = p;
  408.       return (void *) p->data;
  409.     }
  410. }
  411. /* Given ITEM, a pointer to a data item in TREE (or NULL), returns a
  412.    pointer to the next item in the tree in comparison order, or NULL
  413.    if ITEM is the last item. */
  414. void **
  415. avltr_next (const avltr_tree *tree, void **item)
  416. {
  417.   const avltr_node *p;
  418.   assert (tree != NULL);
  419.   if (item == NULL)
  420.     p = &tree->root;
  421.   else
  422.     p = (avltr_node *) (((char *) item) - offsetof (avltr_node, data));
  423.   /* Knuth's Algorithm 2.3.1S (threaded inorder successor). */
  424.   if (p->rtag == MINUS)
  425.     p = p->link[1];
  426.   else
  427.     {
  428.       p = p->link[1];
  429.       while (p->link[0] != NULL)
  430. p = p->link[0];
  431.     }
  432.   if (p == &tree->root)
  433.     return NULL;
  434.   return (void **) &p->data;
  435. }
  436. /* Search TREE for an item matching ITEM.  If found, returns a pointer
  437.    to the address of the item.  If none is found, ITEM is inserted
  438.    into the tree, and a pointer to the address of ITEM is returned.
  439.    In either case, the pointer returned can be changed by the caller,
  440.    or the returned data item can be directly edited, but the key data
  441.    in the item must not be changed. */
  442. void **
  443. avltr_probe (avltr_tree *tree, void *item)
  444. {
  445.   /* Uses Knuth's Algorithm 6.2.3A (balanced tree search and
  446.      insertion), modified for a right-threaded binary tree.  Caches
  447.      results of comparisons.  In empirical tests this eliminates about
  448.      25% of the comparisons seen under random insertions.  */
  449.   /* A1. */
  450.   avltr_node *t;
  451.   avltr_node *s, *p, *q, *r;
  452.   assert (tree != NULL);
  453.   t = &tree->root;
  454.   s = p = t->link[0];
  455.   if (s == NULL)
  456.     {
  457.       tree->count++;
  458.       assert (tree->count == 1);
  459.       q = t->link[0] = xmalloc (sizeof (avltr_node));
  460.       q->data = item;
  461.       q->link[0] = NULL;
  462.       q->link[1] = t;
  463.       q->rtag = MINUS;
  464.       q->bal = 0;
  465.       return &q->data;
  466.     }
  467.   for (;;)
  468.     {
  469.       /* A2. */
  470.       int diff = tree->cmp (item, p->data, tree->param);
  471.       /* A3. */
  472.       if (diff < 0)
  473. {
  474.   p->cache = 0;
  475.   q = p->link[0];
  476.   if (q == NULL)
  477.     {
  478.       /* Algorithm 2.3.1 exercise 23 for insertion to the left
  479.  in a right-threaded binary tree. */
  480.       q = xmalloc (sizeof (avltr_node));
  481.       p->link[0] = q;
  482.       q->link[0] = NULL;
  483.       q->link[1] = p;
  484.       q->rtag = MINUS;
  485.       break;
  486.     }
  487. }
  488.       /* A4. */
  489.       else if (diff > 0)
  490. {
  491.   p->cache = 1;
  492.   q = p->link[1];
  493.   if (p->rtag == MINUS)
  494.     {
  495.       /* Algorithm 2.3.1 exercise 23 for insertion to the right
  496.  in a right-threaded binary tree. */
  497.       q = xmalloc (sizeof (avltr_node));
  498.       q->link[1] = p->link[1];
  499.       q->rtag = p->rtag;
  500.       p->link[1] = q;
  501.       p->rtag = PLUS;
  502.       q->link[0] = NULL;
  503.       break;
  504.     }
  505.   assert (q != NULL);
  506. }
  507.       else
  508. /* A2. */
  509. return &p->data;
  510.       /* A3, A4. */
  511.       if (q->bal != 0)
  512. t = p, s = q;
  513.       p = q;
  514.     }
  515.   
  516.   /* A5. */
  517.   tree->count++;
  518.   q->data = item;
  519.   q->bal = 0;
  520.   
  521.   /* A6. */
  522.   r = p = s->link[(int) s->cache];
  523.   while (p != q)
  524.     {
  525.       p->bal = p->cache * 2 - 1;
  526.       p = p->link[(int) p->cache];
  527.     }
  528.   /* A7. */
  529.   if (s->cache == 0)
  530.     {
  531.       /* a = -1. */
  532.       if (s->bal == 0)
  533. {
  534.   s->bal = -1;
  535.   return &q->data;
  536. }
  537.       else if (s->bal == +1)
  538. {
  539.   s->bal = 0;
  540.   return &q->data;
  541. }
  542.       assert (s->bal == -1);
  543.       if (r->bal == -1)
  544. {
  545.   /* A8. */
  546.   p = r;
  547.   if (r->rtag == MINUS)
  548.     {
  549.       s->link[0] = NULL;
  550.       r->link[1] = s;
  551.       r->rtag = PLUS;
  552.     }
  553.   else
  554.     {
  555.       s->link[0] = r->link[1];
  556.       r->link[1] = s;
  557.     }
  558.   s->bal = r->bal = 0;
  559. }
  560.       else
  561. {
  562.   /* A9. */
  563.   assert (r->bal == +1);
  564.   p = r->link[1];
  565.   r->link[1] = p->link[0];
  566.   p->link[0] = r;
  567.   s->link[0] = p->link[1];
  568.   p->link[1] = s;
  569.   if (p->bal == -1)
  570.     s->bal = 1, r->bal = 0;
  571.   else if (p->bal == 0)
  572.     s->bal = r->bal = 0;
  573.   else 
  574.     {
  575.       assert (p->bal == +1);
  576.       s->bal = 0, r->bal = -1;
  577.     }
  578.   p->bal = 0;
  579.   p->rtag = PLUS;
  580.   if (s->link[0] == s)
  581.     s->link[0] = NULL;
  582.   if (r->link[1] == NULL)
  583.     {
  584.       r->link[1] = p;
  585.       r->rtag = MINUS;
  586.     }
  587. }
  588.     }
  589.   else
  590.     {
  591.       /* a == +1. */
  592.       if (s->bal == 0)
  593. {
  594.   s->bal = 1;
  595.   return &q->data;
  596. }
  597.       else if (s->bal == -1)
  598. {
  599.   s->bal = 0;
  600.   return &q->data;
  601. }
  602.       assert (s->bal == +1);
  603.       if (r->bal == +1)
  604. {
  605.   /* A8. */
  606.   p = r;
  607.   if (r->link[0] == NULL)
  608.     {
  609.       s->rtag = MINUS;
  610.       r->link[0] = s;
  611.     }
  612.   else
  613.     {
  614.       s->link[1] = r->link[0];
  615.       s->rtag = PLUS;
  616.       r->link[0] = s;
  617.     }
  618.   s->bal = r->bal = 0;
  619. }
  620.       else
  621. {
  622.   /* A9. */
  623.   assert (r->bal == -1);
  624.   p = r->link[0];
  625.   r->link[0] = p->link[1];
  626.   p->link[1] = r;
  627.   s->link[1] = p->link[0];
  628.   p->link[0] = s;
  629.   if (p->bal == +1)
  630.     s->bal = -1, r->bal = 0;
  631.   else if (p->bal == 0)
  632.     s->bal = r->bal = 0;
  633.   else 
  634.     {
  635.       assert (p->bal == -1);
  636.       s->bal = 0, r->bal = 1;
  637.     }
  638.   p->rtag = PLUS;
  639.   if (s->link[1] == NULL)
  640.     {
  641.       s->link[1] = p;
  642.       s->rtag = MINUS;
  643.     }
  644.   if (r->link[0] == r)
  645.     r->link[0] = NULL;
  646.   p->bal = 0;
  647. }
  648.     }
  649.   /* A10. */
  650.   if (t != &tree->root && s == t->link[1])
  651.     t->link[1] = p;
  652.   else
  653.     t->link[0] = p;
  654.   return &q->data;
  655. }
  656.   
  657. /* Search TREE for an item matching ITEM, and return a pointer to it
  658.    if found. */
  659. void **
  660. avltr_find (const avltr_tree *tree, const void *item)
  661. {
  662.   const avltr_node *p;
  663.   assert (tree != NULL);
  664.   p = tree->root.link[0];
  665.   if (p == NULL)
  666.     return NULL;
  667.   for (;;)
  668.     {
  669.       int diff = tree->cmp (item, p->data, tree->param);
  670.       /* A3. */
  671.       if (diff < 0)
  672. {
  673.   p = p->link[0];
  674.   if (p == NULL)
  675.     return NULL;
  676. }
  677.       else if (diff > 0)
  678. {
  679.   if (p->rtag == MINUS)
  680.     return NULL;
  681.   p = p->link[1];
  682. }
  683.       else
  684. return (void **) &p->data;
  685.     }
  686. }
  687. /* Search TREE for an item close to the value of ITEM, and return it.
  688.    This function will return a null pointer only if TREE is empty. */
  689. void **
  690. avltr_find_close (const avltr_tree *tree, const void *item)
  691. {
  692.   const avltr_node *p;
  693.   assert (tree != NULL);
  694.   p = tree->root.link[0];
  695.   if (p == NULL)
  696.     return NULL;
  697.   for (;;)
  698.     {
  699.       int diff = tree->cmp (item, p->data, tree->param);
  700.       /* A3. */
  701.       if (diff < 0)
  702. {
  703.   if (p->link[0])
  704.     p = p->link[0];
  705.   else
  706.     return (void **) &p->data;
  707. }
  708.       else if (diff > 0)
  709. {
  710.   if (p->rtag == MINUS)
  711.     return (void **) &p->data;
  712.   p = p->link[1];
  713. }
  714.       else
  715. return (void **) &p->data;
  716.     }
  717. }
  718. /* Searches AVL tree TREE for an item matching ITEM.  If found, the
  719.    item is removed from the tree and the actual item found is returned
  720.    to the caller.  If no item matching ITEM exists in the tree,
  721.    returns NULL. */
  722. void *
  723. avltr_delete (avltr_tree *tree, const void *item)
  724. {
  725.   /* Uses my Algorithm DTR, which can be found at
  726.      http://www.msu.edu/user/pfaffben/avl.  Algorithm DT is based on
  727.      Knuth's Algorithms 6.2.2D (Tree deletion), 6.2.3A (Balanced tree
  728.      search and insertion), 2.3.1I (Insertion into a threaded binary
  729.      trees), and the notes on pages 465-466 of Vol. 3. */
  730.   /* D1. */
  731.   avltr_node *pa[AVL_MAX_HEIGHT]; /* Stack P: Nodes. */
  732.   unsigned char a[AVL_MAX_HEIGHT]; /* Stack P: Bits. */
  733.   int k = 1; /* Stack P: Pointer. */
  734.   
  735.   avltr_node *p;
  736.   assert (tree != NULL);
  737.   a[0] = 0;
  738.   pa[0] = &tree->root;
  739.   p = tree->root.link[0];
  740.   if (p == NULL)
  741.     return NULL;
  742.   for (;;)
  743.     {
  744.       /* D2. */
  745.       int diff = tree->cmp (item, p->data, tree->param);
  746.       if (diff == 0)
  747. break;
  748.       /* D3, D4. */
  749.       pa[k] = p;
  750.       if (diff < 0)
  751. {
  752.   if (p->link[0] != NULL)
  753.     {
  754.       p = p->link[0];
  755.       a[k] = 0;
  756.     }
  757.   else
  758.     return NULL;
  759. }
  760.       else if (diff > 0)
  761. {
  762.   if (p->rtag == PLUS)
  763.     {
  764.       p = p->link[1];
  765.       a[k] = 1;
  766.     }
  767.   else
  768.     return NULL;
  769. }
  770.       k++;
  771.     }
  772.   tree->count--;
  773.   
  774.   item = p->data;
  775.   {
  776.     avltr_node *t = p;
  777.     avltr_node **q = &pa[k - 1]->link[(int) a[k - 1]];
  778.     /* D5. */
  779.     if (t->rtag == MINUS)
  780.       {
  781. if (t->link[0] != NULL)
  782.   {
  783.     avltr_node *const x = t->link[0];
  784.     *q = x;
  785.     (*q)->bal = 0;
  786.     if (x->rtag == MINUS)
  787.       {
  788. if (a[k - 1] == 1)
  789.   x->link[1] = t->link[1];
  790. else
  791.   x->link[1] = pa[k - 1];
  792.       }
  793.   }
  794. else
  795.   {
  796.     *q = t->link[a[k - 1]];
  797.     if (a[k - 1] == 0)
  798.       pa[k - 1]->link[0] = NULL;
  799.     else
  800.       pa[k - 1]->rtag = MINUS;
  801.   }
  802.       }
  803.     else
  804.       {
  805. /* D6. */
  806. avltr_node *r = t->link[1];
  807. if (r->link[0] == NULL)
  808.   {
  809.     r->link[0] = t->link[0];
  810.     r->bal = t->bal;
  811.     if (r->link[0] != NULL)
  812.       {
  813. avltr_node *s = r->link[0];
  814. while (s->rtag == PLUS)
  815.   s = s->link[1];
  816. assert (s->rtag == MINUS);
  817. s->link[1] = r;
  818.       }
  819.     *q = r;
  820.     a[k] = 1;
  821.     pa[k++] = r;
  822.   }
  823. else
  824.   {
  825.     /* D7. */
  826.     avltr_node *s = r->link[0];
  827.     a[k] = 1;
  828.     pa[k++] = t;
  829.     a[k] = 0;
  830.     pa[k++] = r;
  831.     
  832.     /* D8. */
  833.     while (s->link[0] != NULL)
  834.       {
  835. r = s;
  836. s = r->link[0];
  837. a[k] = 0;
  838. pa[k++] = r;
  839.       }
  840.     /* D9. */
  841.     t->data = s->data;
  842.     if (s->rtag == PLUS)
  843.       r->link[0] = s->link[1];
  844.     else
  845.       r->link[0] = NULL;
  846.     p = s;
  847.   }
  848.       }
  849.   }
  850.   xfree (p);
  851.   assert (k > 0);
  852.   /* D10. */
  853.   while (--k)
  854.     {
  855.       avltr_node *const s = pa[k];
  856.       if (a[k] == 0)
  857. {
  858.   avltr_node *const r = s->link[1];
  859.   
  860.   /* D10. */
  861.   if (s->bal == -1)
  862.     {
  863.       s->bal = 0;
  864.       continue;
  865.     }
  866.   else if (s->bal == 0)
  867.     {
  868.       s->bal = +1;
  869.       break;
  870.     }
  871.   assert (s->bal == +1);
  872.   if (s->rtag == MINUS || r->bal == 0)
  873.     {
  874.       /* D11. */
  875.       s->link[1] = r->link[0];
  876.       r->link[0] = s;
  877.       r->bal = -1;
  878.       pa[k - 1]->link[(int) a[k - 1]] = r;
  879.       break;
  880.     }
  881.   else if (r->bal == +1)
  882.     {
  883.       /* D12. */
  884.       if (r->link[0] != NULL)
  885. {
  886.   s->rtag = PLUS;
  887.   s->link[1] = r->link[0];
  888. }
  889.       else
  890. s->rtag = MINUS;
  891.       r->link[0] = s;
  892.       s->bal = r->bal = 0;
  893.       pa[k - 1]->link[a[k - 1]] = r;
  894.     }
  895.   else 
  896.     {
  897.       /* D13. */
  898.       assert (r->bal == -1);
  899.       p = r->link[0];
  900.       if (p->rtag == PLUS)
  901. r->link[0] = p->link[1];
  902.       else
  903. r->link[0] = NULL;
  904.       p->link[1] = r;
  905.       p->rtag = PLUS;
  906.       if (p->link[0] == NULL)
  907. {
  908.   s->link[1] = p;
  909.   s->rtag = MINUS;
  910. }
  911.       else
  912. {
  913.   s->link[1] = p->link[0];
  914.   s->rtag = PLUS;
  915. }
  916.       p->link[0] = s;
  917.       if (p->bal == +1)
  918. s->bal = -1, r->bal = 0;
  919.       else if (p->bal == 0)
  920. s->bal = r->bal = 0;
  921.       else
  922. {
  923.   assert (p->bal == -1);
  924.   s->bal = 0, r->bal = +1;
  925. }
  926.       p->bal = 0;
  927.       pa[k - 1]->link[(int) a[k - 1]] = p;
  928.       if (a[k - 1] == 1)
  929. pa[k - 1]->rtag = PLUS;
  930.     }
  931. }
  932.       else
  933. {
  934.   avltr_node *const r = s->link[0];
  935.   
  936.   /* D10. */
  937.   if (s->bal == +1)
  938.     {
  939.       s->bal = 0;
  940.       continue;
  941.     }
  942.   else if (s->bal == 0)
  943.     {
  944.       s->bal = -1;
  945.       break;
  946.     }
  947.   assert (s->bal == -1);
  948.   if (s->link[0] == NULL || r->bal == 0)
  949.     {
  950.       /* D11. */
  951.       s->link[0] = r->link[1];
  952.       r->link[1] = s;
  953.       r->bal = +1;
  954.       pa[k - 1]->link[(int) a[k - 1]] = r;
  955.       break;
  956.     }
  957.   else if (r->bal == -1)
  958.     {
  959.       /* D12. */
  960.       if (r->rtag == PLUS)
  961. s->link[0] = r->link[1];
  962.       else
  963. s->link[0] = NULL;
  964.       r->link[1] = s;
  965.       r->rtag = PLUS;
  966.       s->bal = r->bal = 0;
  967.       pa[k - 1]->link[a[k - 1]] = r;
  968.     }
  969.   else 
  970.     {
  971.       /* D13. */
  972.       assert (r->bal == +1);
  973.       p = r->link[1];
  974.       if (p->link[0] != NULL)
  975. {
  976.   r->rtag = PLUS;
  977.   r->link[1] = p->link[0];
  978. }
  979.       else
  980. r->rtag = MINUS;
  981.       p->link[0] = r;
  982.       if (p->rtag == MINUS)
  983. s->link[0] = NULL;
  984.       else
  985. s->link[0] = p->link[1];
  986.       p->link[1] = s;
  987.       p->rtag = PLUS;
  988.       if (p->bal == -1)
  989. s->bal = +1, r->bal = 0;
  990.       else if (p->bal == 0)
  991. s->bal = r->bal = 0;
  992.       else
  993. {
  994.   assert (p->bal == +1);
  995.   s->bal = 0, r->bal = -1;
  996. }
  997.       p->bal = 0;
  998.       if (a[k - 1] == 1)
  999. pa[k - 1]->rtag = PLUS;
  1000.       pa[k - 1]->link[(int) a[k - 1]] = p;
  1001.     }
  1002. }
  1003.     }
  1004.       
  1005.   return (void *) item;
  1006. }
  1007. /* Inserts ITEM into TREE.  Returns NULL if the item was inserted,
  1008.    otherwise a pointer to the duplicate item. */
  1009. void *
  1010. avltr_insert (avltr_tree *tree, void *item)
  1011. {
  1012.   void **p;
  1013.   
  1014.   assert (tree != NULL);
  1015.   
  1016.   p = avltr_probe (tree, item);
  1017.   return (*p == item) ? NULL : *p;
  1018. }
  1019. /* If ITEM does not exist in TREE, inserts it and returns NULL.  If a
  1020.    matching item does exist, it is replaced by ITEM and the item
  1021.    replaced is returned.  The caller is responsible for freeing the
  1022.    item returned. */
  1023. void *
  1024. avltr_replace (avltr_tree *tree, void *item)
  1025. {
  1026.   void **p;
  1027.   assert (tree != NULL);
  1028.   
  1029.   p = avltr_probe (tree, item);
  1030.   if (*p == item)
  1031.     return NULL;
  1032.   else
  1033.     {
  1034.       void *r = *p;
  1035.       *p = item;
  1036.       return r;
  1037.     }
  1038. }
  1039. /* Delete ITEM from TREE when you know that ITEM must be in TREE.  For
  1040.    debugging purposes. */
  1041. void *
  1042. (avltr_force_delete) (avltr_tree *tree, void *item)
  1043. {
  1044.   void *found = avltr_delete (tree, item);
  1045.   assert (found != NULL);
  1046.   return found;
  1047. }
  1048. #if SELF_TEST
  1049. /* Size of the tree used for testing. */
  1050. #define TREE_SIZE 1024
  1051. /* Used to flag delayed aborting. */
  1052. int done = 0;
  1053. /* Count the number of nodes in TREE below and including NODE. */
  1054. int
  1055. count (avltr_tree *tree, avltr_node *node)
  1056. {
  1057.   int n = 1;
  1058.   if (node->link[0] != NULL)
  1059.     n += count (tree, node->link[0]);
  1060.   if (node->rtag == PLUS)
  1061.     n += count (tree, node->link[1]);
  1062.   return n;
  1063. }
  1064. /* Print the structure of node NODE of an avl tree, which is LEVEL
  1065.    levels from the top of the tree.  Uses different delimiters to
  1066.    visually distinguish levels. */
  1067. void
  1068. print_structure (avltr_tree *tree, avltr_node *node, int level)
  1069. {
  1070.   char lc[] = "([{<`";
  1071.   char rc[] = ")]}>'";
  1072.   if (node == NULL)
  1073.     {
  1074.       printf (" :nil");
  1075.       return;
  1076.     }
  1077.   else if (level >= 10)
  1078.     {
  1079.       printf ("Too deep, giving up.n");
  1080.       done = 1;
  1081.       return;
  1082.     }
  1083.   else if (node == &tree->root)
  1084.     {
  1085.       printf (" root");
  1086.       return;
  1087.     }
  1088.   printf (" %c%d", lc[level % 5], (int) node->data);
  1089.   fflush (stdout);
  1090.   print_structure (tree, node->link[0], level + 1);
  1091.   fflush (stdout);
  1092.   if (node->rtag == PLUS)
  1093.     print_structure (tree, node->link[1], level + 1);
  1094.   else if (node->link[1] != &tree->root)
  1095.     printf (" :%d", (int) node->link[1]->data);
  1096.   else
  1097.     printf (" :r");
  1098.   fflush (stdout);
  1099.   printf ("%c", rc[level % 5]);
  1100.   fflush (stdout);
  1101. }
  1102. /* Compare two integers A and B and return a strcmp()-type result. */
  1103. int
  1104. compare_ints (const void *a, const void *b, void *param unused)
  1105. {
  1106.   return ((int) a) - ((int) b);
  1107. }
  1108. /* Print the value of integer A. */
  1109. void
  1110. print_int (void *a, void *param unused)
  1111. {
  1112.   printf (" %d", (int) a);
  1113. }
  1114. /* Linearly print contents of TREE. */
  1115. void
  1116. print_contents (avltr_tree *tree)
  1117. {
  1118.   avltr_walk (tree, print_int, NULL);
  1119.   printf ("n");
  1120. }
  1121. /* Examine NODE in a avl tree.  *COUNT is increased by the number of
  1122.    nodes in the tree, including the current one.  If the node is the
  1123.    root of the tree, PARENT should be INT_MIN, otherwise it should be
  1124.    the parent node value.  DIR is the direction that the current node
  1125.    is linked from the parent: -1 for left child, +1 for right child;
  1126.    it is not used if PARENT is INT_MIN.  Returns the height of the
  1127.    tree rooted at NODE. */
  1128. int
  1129. recurse_tree (avltr_tree *tree, avltr_node *node, int *count, int parent,
  1130.       int dir, unsigned char *nodes, unsigned char *threads)
  1131. {
  1132.   if (node != NULL && node != &tree->root) 
  1133.     {
  1134.       int d = (int) node->data;
  1135.       int nl = 0;
  1136.       int nr = 0;
  1137.       (*count)++;
  1138.       assert (d >= 0 && d < TREE_SIZE);
  1139.       if (nodes[d / 8] & (1 << (d % 8)))
  1140. {
  1141.   printf (" Arrived at node %d by two different paths.n", d);
  1142.   done = 1;
  1143. }
  1144.       else
  1145. nodes[d / 8] |= 1 << (d % 8);
  1146.       if (node->link[0] != NULL)
  1147. nl = recurse_tree (tree, node->link[0], count, d, -1, nodes, threads);
  1148.       if (node->rtag == PLUS)
  1149. {
  1150.   if (node->link[1] == NULL)
  1151.     {
  1152.       printf (" Null thread link.n");
  1153.       done = 1;
  1154.     }
  1155.   nr = recurse_tree (tree, node->link[1], count, d, 1, nodes, threads);
  1156. }
  1157.       else if (node->link[1] != &tree->root)
  1158. {
  1159.   int dr = (int) node->link[1]->data;
  1160.   assert (dr >= 0 && dr < TREE_SIZE);
  1161.   if (threads[dr / 8] & (1 << dr % 8))
  1162.     {
  1163.       printf (" Multiple threads to node %d.n", d);
  1164.       done = 1;
  1165.     }
  1166.   threads[dr / 8] |= 1 << (dr % 8);
  1167. }
  1168.       if (nr - nl != node->bal)
  1169. {
  1170.   printf (" Node %d has incorrect balance: right height=%d, "
  1171.   "left height=%d, difference=%d, but balance factor=%d.n",
  1172.   d, nr, nl, nr - nl, node->bal);
  1173.   done = 1;
  1174. }
  1175.       
  1176.       if (node->bal < -1 || node->bal > 1)
  1177. {
  1178.   printf (" Node %d has invalid balance factor %d.n", d, node->bal);
  1179.   done = 1;
  1180. }
  1181.       
  1182.       if (parent != INT_MIN)
  1183. {
  1184.   assert (dir == -1 || dir == +1);
  1185.   if (dir == -1 && d > parent)
  1186.     {
  1187.       printf (" Node %d is smaller than its left child %d.n",
  1188.       parent, d);
  1189.       done = 1;
  1190.     }
  1191.   else if (dir == +1 && d < parent)
  1192.     {
  1193.       printf (" Node %d is larger than its right child %d.n",
  1194.       parent, d);
  1195.       done = 1;
  1196.     }
  1197. }
  1198.       assert (node->bal >= -1 && node->bal <= 1);
  1199.       return 1 + (nl > nr ? nl : nr);
  1200.     }
  1201.   else return 0;
  1202. }
  1203. /* Check that everything about TREE is kosher. */
  1204. void
  1205. verify_tree (avltr_tree *tree)
  1206. {
  1207.   {
  1208.     unsigned char nodes[(TREE_SIZE + 7) / 8];
  1209.     unsigned char threads[(TREE_SIZE + 7) / 8];
  1210.     int count = 0;
  1211.     int i;
  1212.     
  1213.     memset (nodes, 0, (TREE_SIZE + 7) / 8);
  1214.     memset (threads, 0, (TREE_SIZE + 7) / 8);
  1215.   
  1216.     recurse_tree (tree, tree->root.link[0], &count, INT_MIN, 0, nodes,
  1217.   threads);
  1218.     
  1219.     if (count != tree->count)
  1220.       {
  1221. printf (" Tree should have %d nodes, but tree count by recursive "
  1222. "descent is %d.n", tree->count, count);
  1223. done = 1;
  1224.       }
  1225.     for (i = 0; i < TREE_SIZE; i++)
  1226.       {
  1227. int thread = threads[i / 8] & (1 << (i % 8));
  1228. int node = nodes[i / 8] & (1 << (i % 8));
  1229. if (thread && !node)
  1230.   {
  1231.     printf (" A thread leads to ``node'' %d, "
  1232.     "which is not in the tree.", i);
  1233.     done = 1;
  1234.   }
  1235.       }
  1236.   }
  1237.   /* Check threads. */
  1238.   {
  1239.     int count = 0;
  1240.     int last = INT_MIN;
  1241.     void **data = NULL;
  1242.   
  1243.     while (NULL != (data = avltr_next (tree, data)))
  1244.       {
  1245. if (((int) *data) < last)
  1246.   {
  1247.     printf (" Misordered right threads.n");
  1248.     abort ();
  1249.   }
  1250. else if (((int) *data) == last)
  1251.   {
  1252.     printf (" Loop in right threads detected on %d.n", last);
  1253.     abort ();
  1254.   }
  1255. last = (int) *data;
  1256. count++;
  1257.       }
  1258.     if (count != tree->count)
  1259.       {
  1260. printf (" Tree should have %d nodes, but tree count by right threads "
  1261. "is %d.n", tree->count, count);
  1262. done = 1;
  1263.       }
  1264.   }
  1265.   if (done)
  1266.     abort ();
  1267. }
  1268. /* Arrange the N elements of ARRAY in random order. */
  1269. void
  1270. shuffle (int *array, int n)
  1271. {
  1272.   int i;
  1273.   
  1274.   for (i = 0; i < n; i++)
  1275.     {
  1276.       int j = i + rand () % (n - i);
  1277.       int t = array[j];
  1278.       array[j] = array[i];
  1279.       array[i] = t;
  1280.     }
  1281. }
  1282. /* Compares avl trees rooted at A and B, making sure that they are
  1283.    identical. */
  1284. void
  1285. compare_trees (avltr_node *a, avltr_node *b)
  1286. {
  1287.   int diff = 0;
  1288.   
  1289.   assert (a && b);
  1290.   
  1291.   /* Separating these conditions makes it easier to pinpoint bad data
  1292.      under a memory debugger like Checker because each test is a
  1293.      separate statement. */
  1294.   diff |= a->data != b->data;
  1295.   diff |= a->bal != b->bal;
  1296.   diff |= ((a->link[0] != NULL) ^ (b->link[0] != NULL));
  1297.   diff |= ((a->rtag == PLUS) ^ (b->rtag == PLUS));
  1298.   if (diff)
  1299.     {
  1300.       printf (" Copied nodes differ: %d b=%d a->bal=%d b->bal=%d a:",
  1301.       (int) a->data, (int) b->data, a->bal, b->bal);
  1302.       if (a->link[0])
  1303. printf ("l");
  1304.       if (a->link[1])
  1305. printf ("r");
  1306.       printf (" b:");
  1307.       if (b->link[0])
  1308. printf ("l");
  1309.       if (b->link[1])
  1310. printf ("r");
  1311.       printf ("n");
  1312.       abort ();
  1313.     }
  1314.   if (a->link[0] != NULL)
  1315.     compare_trees (a->link[0], b->link[0]);
  1316.   if (a->rtag == PLUS)
  1317.     compare_trees (a->link[1], b->link[1]);
  1318. }
  1319. /* Simple stress test procedure for the AVL tree routines.  Does the
  1320.    following:
  1321.    * Generate a random number seed.  By default this is generated from
  1322.    the current time.  You can also pass a seed value on the command
  1323.    line if you want to test the same case.  The seed value is
  1324.    displayed.
  1325.    * Create a tree and insert the integers from 0 up to TREE_SIZE - 1
  1326.    into it, in random order.  Verify the tree structure after each
  1327.    insertion.
  1328.    
  1329.    * Remove each integer from the tree, in a different random order.
  1330.    After each deletion, verify the tree structure; also, make a copy
  1331.    of the tree into a new tree, verify the copy and compare it to the
  1332.    original, then destroy the copy.
  1333.    * Destroy the tree, increment the random seed value, and start over.
  1334.    If you make any modifications to the avl tree routines, then you
  1335.    might want to insert some calls to print_structure() at strategic
  1336.    places in order to be able to see what's really going on.  Also,
  1337.    memory debuggers like Checker or Purify are very handy. */
  1338. #define N_ITERATIONS 16
  1339. int
  1340. main (int argc, char **argv)
  1341. {
  1342.   int array[TREE_SIZE];
  1343.   int seed;
  1344.   int iteration;
  1345.   
  1346.   if (argc == 2)
  1347.     seed = atoi (argv[1]);
  1348.   else
  1349.     seed = time (0) * 257 % 32768;
  1350.   fputs ("Testing avltr...n", stdout);
  1351.   for (iteration = 1; iteration <= N_ITERATIONS; iteration++)
  1352.     {
  1353.       avltr_tree *tree;
  1354.       int i;
  1355.       
  1356.       printf ("Iteration %4d/%4d: seed=%5d", iteration, N_ITERATIONS, seed);
  1357.       fflush (stdout);
  1358.       
  1359.       srand (seed++);
  1360.       for (i = 0; i < TREE_SIZE; i++)
  1361. array[i] = i;
  1362.       shuffle (array, TREE_SIZE);
  1363.       
  1364.       tree = avltr_create (compare_ints, NULL);
  1365.       for (i = 0; i < TREE_SIZE; i++)
  1366.   avltr_force_insert (tree, (void *) (array[i]));
  1367.       verify_tree (tree);
  1368.       shuffle (array, TREE_SIZE);
  1369.       for (i = 0; i < TREE_SIZE; i++)
  1370. {
  1371.   avltr_tree *copy;
  1372.   avltr_delete (tree, (void *) (array[i]));
  1373.   verify_tree (tree);
  1374.   copy = avltr_copy (tree, NULL);
  1375.   verify_tree (copy);
  1376.   if (tree->root.link[0] != NULL)
  1377.     compare_trees (tree->root.link[0], copy->root.link[0]);
  1378.   else if (copy->root.link[0] != NULL)
  1379.     {
  1380.       printf (" Empty tree results in nonempty copy.n");
  1381.       abort ();
  1382.     }
  1383.   avltr_destroy (copy, NULL);
  1384.   if (i % 128 == 0)
  1385.     {
  1386.       putchar ('.');
  1387.       fflush (stdout);
  1388.     }
  1389. }
  1390.       fputs (" good.n", stdout);
  1391.       avltr_destroy (tree, NULL);
  1392.     }
  1393.   
  1394.   return 0;
  1395. }
  1396. #endif /* SELF_TEST */
  1397. /*
  1398.   Local variables:
  1399.   compile-command: "gcc -DSELF_TEST=1 -W -Wall -I. -o ./avltr-test avltr.c"
  1400.   End:
  1401. */