While working on a general-purpose caching module (out soon), I thought of
[tprouty/samba.git] / source / ubiqx / ubi_BinTree.c
1 /* ========================================================================== **
2  *                              ubi_BinTree.c
3  *
4  *  Copyright (C) 1991-1997 by Christopher R. Hertel
5  *
6  *  Email:  crh@ubiqx.mn.org
7  * -------------------------------------------------------------------------- **
8  *
9  *  This module implements simple binary trees.
10  *
11  * -------------------------------------------------------------------------- **
12  *
13  *  This library is free software; you can redistribute it and/or
14  *  modify it under the terms of the GNU Library General Public
15  *  License as published by the Free Software Foundation; either
16  *  version 2 of the License, or (at your option) any later version.
17  *
18  *  This library is distributed in the hope that it will be useful,
19  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  *  Library General Public License for more details.
22  *
23  *  You should have received a copy of the GNU Library General Public
24  *  License along with this library; if not, write to the Free
25  *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *
27  * -------------------------------------------------------------------------- **
28  *
29  * Log: ubi_BinTree.c,v
30  * Revision 3.0  1997/12/08 06:49:11  crh
31  * This is a new major revision level for all ubiqx binary tree modules.
32  * In previous releases, the ubi_trNode structure looked like this:
33  *
34  *   typedef struct ubi_btNodeStruct
35  *     {
36  *     struct ubi_btNodeStruct *Link[3];
37  *     signed char              gender;
38  *     } ubi_btNode;
39  *
40  * As a result, the pointers were indexed as
41  *
42  *   Link[0] == Left Child
43  *   Link[1] == Parent
44  *   Link[2] == Right Child
45  *
46  * With this release, the node structure changes to:
47  *
48  *   typedef struct ubi_btNodeStruct
49  *     {
50  *     struct ubi_btNodeStruct *leftlink
51  *     struct ubi_btNodeStruct *Link[2];
52  *     signed char              gender;
53  *     } ubi_btNode;
54  *
55  * The leftlink field is used as a place holder, and the pointers are now
56  * index as
57  *
58  *   Link[-1] == Left Child  (aka. leftlink)
59  *   Link[ 0] == Parent
60  *   Link[ 1] == Right Child
61  *
62  * which is much nicer.  Doing things this way removes the need to shift
63  * values between the two numbering schemes, thus removing one macro,
64  * simplifying another, and getting rid of a whole bunch of increment &
65  * decrement operations.
66  *
67  * Revision 2; 1995/02/27 - 1997/12/07 included:
68  *  - The addition of the ModuleID static string and ubi_ModuleID() function.
69  *  - The addition of the public functions FirstOf() and LastOf(). These
70  *    functions are used with trees that allow duplicate keys.
71  *  - The addition of the ubi_btLeafNode() function.
72  *  - A rewrite of the Locate() function.
73  *  - A change to the parameter list in function ubi_btInitTree().
74  *  - Bugfixes.
75  *
76  * Revision 1; 93/10/15 - 95/02/27:
77  * Revision 1 introduced a set of #define's that provide a single API to all
78  * of the existing tree modules.  Each of these modules has a different name
79  * prefix, as follows:
80  *
81  *       Module        Prefix
82  *     ubi_BinTree     ubi_bt
83  *     ubi_AVLtree     ubi_avl
84  *     ubi_SplayTree   ubi_spt
85  *
86  * Only those portions of the base module (ubi_BinTree) that are superceeded
87  * in the descendant module have new names.  For example, the AVL node
88  * structure in ubi_AVLtree.h is named "ubi_avlNode", but the root structure
89  * is still "ubi_btRoot".  Using SplayTree, the locate function is called
90  * "ubi_sptLocate", but the next and previous functions remained "ubi_btNext"
91  * and "ubi_btPrev".
92  *
93  * This is confusing.
94  *
95  * So, I added a set of defined names that get redefined in any of the
96  * descendant modules.  To use this standardized interface in your code,
97  * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
98  * "ubi_tr".  The "ubi_tr" names will resolve to the correct function or
99  * datatype names for the module that you are using.  Just remember to
100  * include the header for that module in your program file.  Because these
101  * names are handled by the preprocessor, there is no added run-time
102  * overhead.
103  *
104  * Note that the original names do still exist, and can be used if you wish
105  * to write code directly to a specific module.  This should probably only be
106  * done if you are planning to implement a new descendant type, such as
107  * red/black trees, or if you plan to use two or more specific tree types
108  * in the same piece of code.  CRH
109  *
110  *  V0.0 - June, 1991   -  Written by Christopher R. Hertel (CRH).
111  *
112  * ========================================================================== **
113  */
114
115 #include "ubi_BinTree.h"            /* Header for this module          */
116 #include <stdlib.h>                 /* Standard C definitions.         */
117
118 /* ========================================================================== **
119  * Static data.
120  */
121
122 static char ModuleID[] = "ubi_BinTree\n\
123 \tRevision: 3.0\n\
124 \tDate: 1997/12/08 06:49:11\n\
125 \tAuthor: crh\n";
126
127 /* ========================================================================== **
128  * Internal (private) functions.
129  */
130
131 static ubi_btNodePtr qFind( ubi_btCompFunc cmp,
132                             ubi_btItemPtr  FindMe,
133                    register ubi_btNodePtr  p )
134   /* ------------------------------------------------------------------------ **
135    * This function performs a non-recursive search of a tree for a node
136    * matching a specific key.  It is called "qFind()" because it is
137    * (probably a little bit) faster that TreeFind (below).
138    *
139    *  Input:
140    *     cmp      -  a pointer to the tree's comparison function.
141    *     FindMe   -  a pointer to the key value for which to search.
142    *     p        -  a pointer to the starting point of the search.  <p>
143    *                 is considered to be the root of a subtree, and only
144    *                 the subtree will be searched.
145    *
146    *  Output:
147    *     A pointer to a node with a key that matches the key indicated by
148    *     FindMe, or NULL if no such node was found.
149    *
150    *  Note:   In a tree that allows duplicates, the pointer returned *might
151    *          not* point to the (sequentially) first occurance of the
152    *          desired key.
153    * ------------------------------------------------------------------------ **
154    */
155   {
156   signed char tmp;
157
158   while( p && (( tmp = ubi_trNormalize((*cmp)(FindMe, p)) ) != ubi_trEQUAL) )
159     p = p->Link[tmp];
160
161   return( p );
162   } /* qFind */
163
164 static ubi_btNodePtr TreeFind( ubi_btItemPtr  findme,
165                                ubi_btNodePtr  p,
166                                ubi_btNodePtr *parentp,
167                                signed char   *gender,
168                                ubi_btCompFunc CmpFunc )
169   /* ------------------------------------------------------------------------ **
170    * TreeFind() searches a tree for a given value (findme).  It will return a
171    * pointer to the target node, if found, or NULL if the target node was not
172    * found.
173    *
174    * TreeFind() also returns, via parameters, a pointer to the parent of the
175    * target node, and a LEFT or RIGHT value indicating which child of the
176    * parent is the target node.  *If the target is not found*, then these
177    * values indicate the place at which the target *should be found*.  This
178    * is useful when inserting a new node into a tree or searching for nodes
179    * "near" the target node.
180    *
181    * The parameters are:
182    *
183    *  findme   -  is a pointer to the key information to be searched for.
184    *  p        -  points to the root of the tree to be searched.
185    *  parentp  -  will return a pointer to a pointer to the !parent! of the
186    *              target node, which can be especially usefull if the target
187    *              was not found.
188    *  gender   -  returns LEFT or RIGHT to indicate which child of *parentp
189    *              was last searched.
190    *  CmpFunc  -  points to the comparison function.
191    *
192    * This function is called by ubi_btLocate() and ubi_btInsert().
193    * ------------------------------------------------------------------------ **
194    */
195   {
196   register ubi_btNodePtr tmp_p = p;
197   ubi_btNodePtr tmp_pp         = NULL;
198   signed char   tmp_gender     = ubi_trEQUAL;
199   signed char   tmp_cmp;
200
201   while( tmp_p
202       && (ubi_trEQUAL != (tmp_cmp = ubi_trNormalize((*CmpFunc)(findme, tmp_p))))
203        )
204     {
205     tmp_pp  = tmp_p;                /* Keep track of previous node. */
206     tmp_gender = tmp_cmp;           /* Keep track of sex of child.  */
207     tmp_p = tmp_p->Link[tmp_cmp];   /* Go to child. */
208     }
209   *parentp = tmp_pp;                /* Return results. */
210   *gender  = tmp_gender;
211   return( tmp_p );
212   } /* TreeFind */
213
214 static void ReplaceNode( ubi_btNodePtr *parent,
215                          ubi_btNodePtr  oldnode,
216                          ubi_btNodePtr  newnode )
217   /* ------------------------------------------------------------------------ **
218    * Remove node oldnode from the tree, replacing it with node newnode.
219    *
220    * Input:
221    *  parent   - A pointer to he parent pointer of the node to be
222    *             replaced.  <parent> may point to the Link[] field of
223    *             a parent node, or it may indicate the root pointer at
224    *             the top of the tree.
225    *  oldnode  - A pointer to the node that is to be replaced.
226    *  newnode  - A pointer to the node that is to be installed in the
227    *             place of <*oldnode>.
228    *
229    * Notes:    Don't forget to free oldnode.
230    *
231    * ------------------------------------------------------------------------ **
232    */
233   {
234   register int i;
235   register int btNodeSize = sizeof( ubi_btNode );
236
237   for( i = 0; i < btNodeSize; i++ ) /* Copy node internals to new node. */
238     ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
239
240   /* Old node's parent points to new child. */
241   (*parent) = newnode;
242
243   /* Now tell the children about their new step-parent. */
244   if( oldnode->Link[ubi_trLEFT ] )
245     (oldnode->Link[ubi_trLEFT ])->Link[ubi_trPARENT] = newnode;
246
247   if( oldnode->Link[ubi_trRIGHT] )
248     (oldnode->Link[ubi_trRIGHT])->Link[ubi_trPARENT] = newnode;
249
250   } /* ReplaceNode */
251
252 static void SwapNodes( ubi_btRootPtr RootPtr,
253                        ubi_btNodePtr Node1,
254                        ubi_btNodePtr Node2 )
255   /* ------------------------------------------------------------------------ **
256    * This function swaps two nodes in the tree.  Node1 will take the place of
257    * Node2, and Node2 will fill in the space left vacant by Node 1.
258    *
259    * Input:
260    *  RootPtr  - pointer to the tree header structure for this tree.
261    *  Node1    - \
262    *              > These are the two nodes which are to be swapped.
263    *  Node2    - /
264    *
265    * Notes:
266    *  This function does a three step swap, using a dummy node as a place
267    *  holder.  This function is used by ubi_btRemove().
268    * ------------------------------------------------------------------------ **
269    */
270   {
271   ubi_btNodePtr *Parent;
272   ubi_btNode     dummy;
273   ubi_btNodePtr  dummy_p = &dummy;
274
275   /* Replace Node 1 with the dummy, thus removing Node1 from the tree. */
276   if( Node1->Link[ubi_trPARENT] )
277     Parent = &((Node1->Link[ubi_trPARENT])->Link[Node1->gender]);
278   else
279     Parent = &(RootPtr->root);
280   ReplaceNode( Parent, Node1, dummy_p );
281
282   /* Swap Node 1 with Node 2, placing Node 1 back into the tree. */
283   if( Node2->Link[ubi_trPARENT] )
284     Parent = &((Node2->Link[ubi_trPARENT])->Link[Node2->gender]);
285   else
286     Parent = &(RootPtr->root);
287   ReplaceNode( Parent, Node2, Node1 );
288
289   /* Swap Node 2 and the dummy, thus placing Node 2 back into the tree. */
290   if( dummy_p->Link[ubi_trPARENT] )
291     Parent = &((dummy_p->Link[ubi_trPARENT])->Link[dummy_p->gender]);
292   else
293     Parent = &(RootPtr->root);
294   ReplaceNode( Parent, dummy_p, Node2 );
295   } /* SwapNodes */
296
297 /* -------------------------------------------------------------------------- **
298  * These routines allow you to walk through the tree, forwards or backwards.
299  */
300
301 static ubi_btNodePtr SubSlide( register ubi_btNodePtr P,
302                                register signed char   whichway )
303   /* ------------------------------------------------------------------------ **
304    * Slide down the side of a subtree.
305    *
306    * Given a starting node, this function returns a pointer to the LEFT-, or
307    * RIGHT-most descendent, *or* (if whichway is PARENT) to the tree root.
308    *
309    *  Input:  P         - a pointer to a starting place.
310    *          whichway  - the direction (LEFT, RIGHT, or PARENT) in which to
311    *                      travel.
312    *  Output: A pointer to a node that is either the root, or has no
313    *          whichway-th child but is within the subtree of P.  Note that
314    *          the return value may be the same as P.  The return value *will
315    *          be* NULL if P is NULL.
316    * ------------------------------------------------------------------------ **
317    */
318   {
319   ubi_btNodePtr Q = NULL;
320
321   while( P )
322     {
323     Q = P;
324     P = P->Link[ whichway ];
325     }
326   return( Q );
327   } /* SubSlide */
328
329 static ubi_btNodePtr Neighbor( register ubi_btNodePtr P,
330                                register signed char   whichway )
331   /* ------------------------------------------------------------------------ **
332    * Given starting point p, return the (key order) next or preceeding node
333    * in the tree.
334    *
335    *  Input:  P         - Pointer to our starting place node.
336    *          whichway  - the direction in which to travel to find the
337    *                      neighbor, i.e., the RIGHT neighbor or the LEFT
338    *                      neighbor.
339    *
340    *  Output: A pointer to the neighboring node, or NULL if P was NULL.
341    *
342    *  Notes:  If whichway is PARENT, the results are unpredictable.
343    * ------------------------------------------------------------------------ **
344    */
345   {
346   if( P )
347     {
348     if( P->Link[ whichway ] )
349       return( SubSlide( P->Link[ whichway ], ubi_trRevWay(whichway) ) );
350     else
351       while( P->Link[ ubi_trPARENT ] )
352         {
353         if( (P->Link[ ubi_trPARENT ])->Link[ whichway ] == P )
354           P = P->Link[ ubi_trPARENT ];
355         else
356           return( P->Link[ ubi_trPARENT ] );
357         }
358     }
359   return( NULL );
360   } /* Neighbor */
361
362 static ubi_btNodePtr Border( ubi_btRootPtr RootPtr,
363                              ubi_btItemPtr FindMe,
364                              ubi_btNodePtr p,
365                              signed char   whichway )
366   /* ------------------------------------------------------------------------ **
367    * Given starting point p, which has a key value equal to *FindMe, locate
368    * the first (index order) node with the same key value.
369    *
370    * This function is useful in trees that have can have duplicate keys.
371    * For example, consider the following tree:
372    *     Tree                                                      Traversal
373    *       2    If <p> points to the root and <whichway> is RIGHT,     3
374    *      / \    then the return value will be a pointer to the       / \
375    *     2   2    RIGHT child of the root node.  The tree on         2   5
376    *    /   / \    the right shows the order of traversal.          /   / \
377    *   1   2   3                                                   1   4   6
378    *
379    *  Input:  RootPtr   - Pointer to the tree root structure.
380    *          FindMe    - Key value for comparisons.
381    *          p         - Pointer to the starting-point node.
382    *          whichway  - the direction in which to travel to find the
383    *                      neighbor, i.e., the RIGHT neighbor or the LEFT
384    *                      neighbor.
385    *
386    *  Output: A pointer to the first (index, or "traversal", order) node with
387    *          a Key value that matches *FindMe.
388    *
389    *  Notes:  If whichway is PARENT, or if the tree does not allow duplicate
390    *          keys, this function will return <p>.
391    * ------------------------------------------------------------------------ **
392    */
393   {
394   register ubi_btNodePtr q;
395
396   /* Exit if there's nothing that can be done. */
397   if( !ubi_trDups_OK( RootPtr ) || (ubi_trPARENT == whichway) )
398     return( p );
399
400   /* First, if needed, move up the tree.  We need to get to the root of the
401    * subtree that contains all of the matching nodes.
402    */
403   q = p->Link[ubi_trPARENT];
404   while( q && (ubi_trEQUAL == ubi_trNormalize( (*(RootPtr->cmp))(FindMe, q) )) )
405     {
406     p = q;
407     q = p->Link[ubi_trPARENT];
408     }
409
410   /* Next, move back down in the "whichway" direction. */
411   q = p->Link[whichway];
412   while( q )
413     {
414     if( q = qFind( RootPtr->cmp, FindMe, q ) )
415       {
416       p = q;
417       q = p->Link[whichway];
418       }
419     }
420   return( p );
421   } /* Border */
422
423
424 /* ========================================================================== **
425  * Exported utilities.
426  */
427
428 long ubi_btSgn( register long x )
429   /* ------------------------------------------------------------------------ **
430    * Return the sign of x; {negative,zero,positive} ==> {-1, 0, 1}.
431    *
432    *  Input:  x - a signed long integer value.
433    *
434    *  Output: -1, 0, or 1 representing the "sign" of x as follows:
435    *            -1 == negative
436    *             0 == zero (no sign)
437    *             1 == positive
438    *
439    * Note:    This utility is provided in order to facilitate the conversion
440    *          of C comparison function return values into BinTree direction
441    *          values: {ubi_trLEFT, ubi_trPARENT, ubi_trEQUAL}.  It is
442    *          incorporated into the ubi_trNormalize() conversion macro.
443    *
444    * ------------------------------------------------------------------------ **
445    */
446   {
447   return( (x)?((x>0)?(1):(-1)):(0) );
448   } /* ubi_btSgn */
449
450 ubi_btNodePtr ubi_btInitNode( ubi_btNodePtr NodePtr )
451   /* ------------------------------------------------------------------------ **
452    * Initialize a tree node.
453    *
454    *  Input:  a pointer to a ubi_btNode structure to be initialized.
455    *  Output: a pointer to the initialized ubi_btNode structure (ie. the
456    *          same as the input pointer).
457    * ------------------------------------------------------------------------ **
458    */
459   {
460   NodePtr->Link[ ubi_trLEFT ]   = NULL;
461   NodePtr->Link[ ubi_trPARENT ] = NULL;
462   NodePtr->Link[ ubi_trRIGHT ]  = NULL;
463   NodePtr->gender               = ubi_trEQUAL;
464   return( NodePtr );
465   } /* ubi_btInitNode */
466
467 ubi_btRootPtr ubi_btInitTree( ubi_btRootPtr   RootPtr,
468                               ubi_btCompFunc  CompFunc,
469                               unsigned char   Flags )
470   /* ------------------------------------------------------------------------ **
471    * Initialize the fields of a Tree Root header structure.
472    *
473    *  Input:   RootPtr   - a pointer to an ubi_btRoot structure to be
474    *                       initialized.
475    *           CompFunc  - a pointer to a comparison function that will be used
476    *                       whenever nodes in the tree must be compared against
477    *                       outside values.
478    *           Flags     - One bytes worth of flags.  Flags include
479    *                       ubi_trOVERWRITE and ubi_trDUPKEY.  See the header
480    *                       file for more info.
481    *
482    *  Output:  a pointer to the initialized ubi_btRoot structure (ie. the
483    *           same value as RootPtr).
484    *
485    *  Note:    The interface to this function has changed from that of
486    *           previous versions.  The <Flags> parameter replaces two
487    *           boolean parameters that had the same basic effect.
488    *
489    * ------------------------------------------------------------------------ **
490    */
491   {
492   if( RootPtr )
493     {
494     RootPtr->root   = NULL;
495     RootPtr->count  = 0L;
496     RootPtr->cmp    = CompFunc;
497     RootPtr->flags  = (Flags & ubi_trDUPKEY) ? ubi_trDUPKEY : Flags;
498     }                 /* There are only two supported flags, and they are
499                        * mutually exclusive.  ubi_trDUPKEY takes precedence
500                        * over ubi_trOVERWRITE.
501                        */
502   return( RootPtr );
503   } /* ubi_btInitTree */
504
505 ubi_trBool ubi_btInsert( ubi_btRootPtr  RootPtr,
506                          ubi_btNodePtr  NewNode,
507                          ubi_btItemPtr  ItemPtr,
508                          ubi_btNodePtr *OldNode )
509   /* ------------------------------------------------------------------------ **
510    * This function uses a non-recursive algorithm to add a new element to the
511    * tree.
512    *
513    *  Input:   RootPtr  -  a pointer to the ubi_btRoot structure that indicates
514    *                       the root of the tree to which NewNode is to be added.
515    *           NewNode  -  a pointer to an ubi_btNode structure that is NOT
516    *                       part of any tree.
517    *           ItemPtr  -  A pointer to the sort key that is stored within
518    *                       *NewNode.  ItemPtr MUST point to information stored
519    *                       in *NewNode or an EXACT DUPLICATE.  The key data
520    *                       indicated by ItemPtr is used to place the new node
521    *                       into the tree.
522    *           OldNode  -  a pointer to an ubi_btNodePtr.  When searching
523    *                       the tree, a duplicate node may be found.  If
524    *                       duplicates are allowed, then the new node will
525    *                       be simply placed into the tree.  If duplicates
526    *                       are not allowed, however, then one of two things
527    *                       may happen.
528    *                       1) if overwritting *is not* allowed, this
529    *                          function will return FALSE (indicating that
530    *                          the new node could not be inserted), and
531    *                          *OldNode will point to the duplicate that is
532    *                          still in the tree.
533    *                       2) if overwritting *is* allowed, then this
534    *                          function will swap **OldNode for *NewNode.
535    *                          In this case, *OldNode will point to the node
536    *                          that was removed (thus allowing you to free
537    *                          the node).
538    *                          **  If you are using overwrite mode, ALWAYS  **
539    *                          ** check the return value of this parameter! **
540    *                 Note: You may pass NULL in this parameter, the
541    *                       function knows how to cope.  If you do this,
542    *                       however, there will be no way to return a
543    *                       pointer to an old (ie. replaced) node (which is
544    *                       a problem if you are using overwrite mode).
545    *
546    *  Output:  a boolean value indicating success or failure.  The function
547    *           will return FALSE if the node could not be added to the tree.
548    *           Such failure will only occur if duplicates are not allowed,
549    *           nodes cannot be overwritten, AND a duplicate key was found
550    *           within the tree.
551    * ------------------------------------------------------------------------ **
552    */
553   {
554   ubi_btNodePtr OtherP,
555                 parent = NULL;
556   signed char   tmp;
557
558   if( !(OldNode) )       /* If they didn't give us a pointer, supply our own. */
559     OldNode = &OtherP;
560
561   (void)ubi_btInitNode( NewNode );     /* Init the new node's BinTree fields. */
562
563   /* Find a place for the new node. */
564   *OldNode = TreeFind(ItemPtr, (RootPtr->root), &parent, &tmp, (RootPtr->cmp));
565
566   /* Now add the node to the tree... */
567   if (!(*OldNode)) /* The easy one: we have a space for a new node! */
568     {
569     if (!(parent))
570       RootPtr->root = NewNode;
571     else
572       {
573       parent->Link[tmp]           = NewNode;
574       NewNode->Link[ubi_trPARENT] = parent;
575       NewNode->gender             = tmp;
576       }
577     (RootPtr->count)++;
578     return( ubi_trTRUE );
579     }
580
581   /* If we reach this point, we know that a duplicate node exists.  This
582    * section adds the node to the tree if duplicate keys are allowed.
583    */
584   if( ubi_trDups_OK(RootPtr) )    /* Key exists, add duplicate */
585     {
586     ubi_btNodePtr q;
587
588     tmp = ubi_trRIGHT;
589     q = (*OldNode);
590     *OldNode = NULL;
591     while( q )
592       {
593       parent = q;
594       if( tmp == ubi_trEQUAL )
595         tmp = ubi_trRIGHT;
596       q = q->Link[tmp];
597       if ( q )
598         tmp = ubi_trNormalize( (*(RootPtr->cmp))(ItemPtr, q) );
599       }
600     parent->Link[tmp]            = NewNode;
601     NewNode->Link[ubi_trPARENT]  = parent;
602     NewNode->gender              = tmp;
603     (RootPtr->count)++;
604     return( ubi_trTRUE );
605     }
606
607   /* If we get to *this* point, we know that we are not allowed to have
608    * duplicate nodes, but our node keys match, so... may we replace the
609    * old one?
610    */
611   if( ubi_trOvwt_OK(RootPtr) )    /* Key exists, we replace */
612     {
613     if (!(parent))
614       ReplaceNode( &(RootPtr->root), *OldNode, NewNode );
615     else
616       ReplaceNode( &(parent->Link[(*OldNode)->gender]), *OldNode, NewNode );
617     return( ubi_trTRUE );
618     }
619
620   return( ubi_trFALSE );      /* Failure: could not replace an existing node. */
621   } /* ubi_btInsert */
622
623 ubi_btNodePtr ubi_btRemove( ubi_btRootPtr RootPtr,
624                             ubi_btNodePtr DeadNode )
625   /* ------------------------------------------------------------------------ **
626    * This function removes the indicated node from the tree.
627    *
628    *  Input:   RootPtr  -  A pointer to the header of the tree that contains
629    *                       the node to be removed.
630    *           DeadNode -  A pointer to the node that will be removed.
631    *
632    *  Output:  This function returns a pointer to the node that was removed
633    *           from the tree (ie. the same as DeadNode).
634    *
635    *  Note:    The node MUST be in the tree indicated by RootPtr.  If not,
636    *           strange and evil things will happen to your trees.
637    * ------------------------------------------------------------------------ **
638    */
639   {
640   ubi_btNodePtr p,
641                *parentp;
642   signed char   tmp;
643
644   /* if the node has both left and right subtrees, then we have to swap
645    * it with another node.  The other node we choose will be the Prev()ious
646    * node, which is garunteed to have no RIGHT child.
647    */
648   if( (DeadNode->Link[ubi_trLEFT]) && (DeadNode->Link[ubi_trRIGHT]) )
649     SwapNodes( RootPtr, DeadNode, ubi_btPrev( DeadNode ) );
650
651   /* The parent of the node to be deleted may be another node, or it may be
652    * the root of the tree.  Since we're not sure, it's best just to have
653    * a pointer to the parent pointer, whatever it is.
654    */
655   if (DeadNode->Link[ubi_trPARENT])
656     parentp = &((DeadNode->Link[ubi_trPARENT])->Link[DeadNode->gender]);
657   else
658     parentp = &( RootPtr->root );
659
660   /* Now link the parent to the only grand-child and patch up the gender. */
661   tmp = ((DeadNode->Link[ubi_trLEFT]) ? ubi_trLEFT : ubi_trRIGHT);
662
663   p = (DeadNode->Link[tmp]);
664   if( p )
665     {
666     p->Link[ubi_trPARENT] = DeadNode->Link[ubi_trPARENT];
667     p->gender             = DeadNode->gender;
668     }
669   (*parentp) = p;
670
671   /* Finished, reduce the node count and return. */
672   (RootPtr->count)--;
673   return( DeadNode );
674   } /* ubi_btRemove */
675
676 ubi_btNodePtr ubi_btLocate( ubi_btRootPtr RootPtr,
677                             ubi_btItemPtr FindMe,
678                             ubi_trCompOps CompOp )
679   /* ------------------------------------------------------------------------ **
680    * The purpose of ubi_btLocate() is to find a node or set of nodes given
681    * a target value and a "comparison operator".  The Locate() function is
682    * more flexible and (in the case of trees that may contain dupicate keys)
683    * more precise than the ubi_btFind() function.  The latter is faster,
684    * but it only searches for exact matches and, if the tree contains
685    * duplicates, Find() may return a pointer to any one of the duplicate-
686    * keyed records.
687    *
688    *  Input:
689    *     RootPtr  -  A pointer to the header of the tree to be searched.
690    *     FindMe   -  An ubi_btItemPtr that indicates the key for which to
691    *                 search.
692    *     CompOp   -  One of the following:
693    *                    CompOp     Return a pointer to the node with
694    *                    ------     ---------------------------------
695    *                   ubi_trLT - the last key value that is less
696    *                              than FindMe.
697    *                   ubi_trLE - the first key matching FindMe, or
698    *                              the last key that is less than
699    *                              FindMe.
700    *                   ubi_trEQ - the first key matching FindMe.
701    *                   ubi_trGE - the first key matching FindMe, or the
702    *                              first key greater than FindMe.
703    *                   ubi_trGT - the first key greater than FindMe.
704    *  Output:
705    *     A pointer to the node matching the criteria listed above under
706    *     CompOp, or NULL if no node matched the criteria.
707    *
708    *  Notes:
709    *     In the case of trees with duplicate keys, Locate() will behave as
710    *     follows:
711    *
712    *     Find:  3                       Find: 3
713    *     Keys:  1 2 2 2 3 3 3 3 3 4 4   Keys: 1 1 2 2 2 4 4 5 5 5 6
714    *                  ^ ^         ^                   ^ ^
715    *                 LT EQ        GT                 LE GE
716    *
717    *     That is, when returning a pointer to a node with a key that is LESS
718    *     THAN the target key (FindMe), Locate() will return a pointer to the
719    *     LAST matching node.
720    *     When returning a pointer to a node with a key that is GREATER
721    *     THAN the target key (FindMe), Locate() will return a pointer to the
722    *     FIRST matching node.
723    *
724    *  See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
725    * ------------------------------------------------------------------------ **
726    */
727   {
728   register ubi_btNodePtr p;
729   ubi_btNodePtr   parent;
730   signed char     whichkid;
731
732   /* Start by searching for a matching node. */
733   p = TreeFind( FindMe,
734                 RootPtr->root,
735                 &parent,
736                 &whichkid,
737                 RootPtr->cmp );
738
739   if( p )   /* If we have found a match, we can resolve as follows: */
740     {
741     switch( CompOp )
742       {
743       case ubi_trLT:            /* It's just a jump to the left...  */
744         p = Border( RootPtr, FindMe, p, ubi_trLEFT );
745         return( Neighbor( p, ubi_trLEFT ) );
746       case ubi_trGT:            /* ...and then a jump to the right. */
747         p = Border( RootPtr, FindMe, p, ubi_trRIGHT );
748         return( Neighbor( p, ubi_trRIGHT ) );
749       }
750     p = Border( RootPtr, FindMe, p, ubi_trLEFT );
751     return( p );
752     }
753
754   /* Else, no match. */
755   if( ubi_trEQ == CompOp )    /* If we were looking for an exact match... */
756     return( NULL );           /* ...forget it.                            */
757
758   /* We can still return a valid result for GT, GE, LE, and LT.
759    * <parent> points to a node with a value that is either just before or
760    * just after the target value.
761    * Remaining possibilities are LT and GT (including LE & GE).
762    */
763   if( (ubi_trLT == CompOp) || (ubi_trLE == CompOp) )
764     return( (ubi_trLEFT  == whichkid) ? Neighbor( parent, whichkid ) : parent );
765   else
766     return( (ubi_trRIGHT == whichkid) ? Neighbor( parent, whichkid ) : parent );
767   } /* ubi_btLocate */
768
769 ubi_btNodePtr ubi_btFind( ubi_btRootPtr RootPtr,
770                           ubi_btItemPtr FindMe )
771   /* ------------------------------------------------------------------------ **
772    * This function performs a non-recursive search of a tree for any node
773    * matching a specific key.
774    *
775    *  Input:
776    *     RootPtr  -  a pointer to the header of the tree to be searched.
777    *     FindMe   -  a pointer to the key value for which to search.
778    *
779    *  Output:
780    *     A pointer to a node with a key that matches the key indicated by
781    *     FindMe, or NULL if no such node was found.
782    *
783    *  Note:   In a tree that allows duplicates, the pointer returned *might
784    *          not* point to the (sequentially) first occurance of the
785    *          desired key.  In such a tree, it may be more useful to use
786    *          ubi_btLocate().
787    * ------------------------------------------------------------------------ **
788    */
789   {
790   return( qFind( RootPtr->cmp, FindMe, RootPtr->root ) );
791   } /* ubi_btFind */
792
793 ubi_btNodePtr ubi_btNext( ubi_btNodePtr P )
794   /* ------------------------------------------------------------------------ **
795    * Given the node indicated by P, find the (sorted order) Next node in the
796    * tree.
797    *  Input:   P  -  a pointer to a node that exists in a binary tree.
798    *  Output:  A pointer to the "next" node in the tree, or NULL if P pointed
799    *           to the "last" node in the tree or was NULL.
800    * ------------------------------------------------------------------------ **
801    */
802   {
803   return( Neighbor( P, ubi_trRIGHT ) );
804   } /* ubi_btNext */
805
806 ubi_btNodePtr ubi_btPrev( ubi_btNodePtr P )
807   /* ------------------------------------------------------------------------ **
808    * Given the node indicated by P, find the (sorted order) Previous node in
809    * the tree.
810    *  Input:   P  -  a pointer to a node that exists in a binary tree.
811    *  Output:  A pointer to the "previous" node in the tree, or NULL if P
812    *           pointed to the "first" node in the tree or was NULL.
813    * ------------------------------------------------------------------------ **
814    */
815   {
816   return( Neighbor( P, ubi_trLEFT ) );
817   } /* ubi_btPrev */
818
819 ubi_btNodePtr ubi_btFirst( ubi_btNodePtr P )
820   /* ------------------------------------------------------------------------ **
821    * Given the node indicated by P, find the (sorted order) First node in the
822    * subtree of which *P is the root.
823    *  Input:   P  -  a pointer to a node that exists in a binary tree.
824    *  Output:  A pointer to the "first" node in a subtree that has *P as its
825    *           root.  This function will return NULL only if P is NULL.
826    *  Note:    In general, you will be passing in the value of the root field
827    *           of an ubi_btRoot structure.
828    * ------------------------------------------------------------------------ **
829    */
830   {
831   return( SubSlide( P, ubi_trLEFT ) );
832   } /* ubi_btFirst */
833
834 ubi_btNodePtr ubi_btLast( ubi_btNodePtr P )
835   /* ------------------------------------------------------------------------ **
836    * Given the node indicated by P, find the (sorted order) Last node in the
837    * subtree of which *P is the root.
838    *  Input:   P  -  a pointer to a node that exists in a binary tree.
839    *  Output:  A pointer to the "last" node in a subtree that has *P as its
840    *           root.  This function will return NULL only if P is NULL.
841    *  Note:    In general, you will be passing in the value of the root field
842    *           of an ubi_btRoot structure.
843    * ------------------------------------------------------------------------ **
844    */
845   {
846   return( SubSlide( P, ubi_trRIGHT ) );
847   } /* ubi_btLast */
848
849 ubi_btNodePtr ubi_btFirstOf( ubi_btRootPtr RootPtr,
850                              ubi_btItemPtr MatchMe,
851                              ubi_btNodePtr p )
852   /* ------------------------------------------------------------------------ **
853    * Given a tree that a allows duplicate keys, and a pointer to a node in
854    * the tree, this function will return a pointer to the first (traversal
855    * order) node with the same key value.
856    *
857    *  Input:  RootPtr - A pointer to the root of the tree.
858    *          MatchMe - A pointer to the key value.  This should probably
859    *                    point to the key within node *p.
860    *          p       - A pointer to a node in the tree.
861    *  Output: A pointer to the first node in the set of nodes with keys
862    *          matching <FindMe>.
863    *  Notes:  Node *p MUST be in the set of nodes with keys matching
864    *          <FindMe>.  If not, this function will return NULL.
865    * ------------------------------------------------------------------------ **
866    */
867   {
868   /* If our starting point is invalid, return NULL. */
869   if( !p || ubi_trNormalize( (*(RootPtr->cmp))( MatchMe, p ) != ubi_trEQUAL ) )
870     return( NULL );
871   return( Border( RootPtr, MatchMe, p, ubi_trLEFT ) );
872   } /* ubi_btFirstOf */
873
874 ubi_btNodePtr ubi_btLastOf( ubi_btRootPtr RootPtr,
875                             ubi_btItemPtr MatchMe,
876                             ubi_btNodePtr p )
877   /* ------------------------------------------------------------------------ **
878    * Given a tree that a allows duplicate keys, and a pointer to a node in
879    * the tree, this function will return a pointer to the last (traversal
880    * order) node with the same key value.
881    *
882    *  Input:  RootPtr - A pointer to the root of the tree.
883    *          MatchMe - A pointer to the key value.  This should probably
884    *                    point to the key within node *p.
885    *          p       - A pointer to a node in the tree.
886    *  Output: A pointer to the last node in the set of nodes with keys
887    *          matching <FindMe>.
888    *  Notes:  Node *p MUST be in the set of nodes with keys matching
889    *          <FindMe>.  If not, this function will return NULL.
890    * ------------------------------------------------------------------------ **
891    */
892   {
893   /* If our starting point is invalid, return NULL. */
894   if( !p || ubi_trNormalize( (*(RootPtr->cmp))( MatchMe, p ) != ubi_trEQUAL ) )
895     return( NULL );
896   return( Border( RootPtr, MatchMe, p, ubi_trRIGHT ) );
897   } /* ubi_btLastOf */
898
899 ubi_trBool ubi_btTraverse( ubi_btRootPtr   RootPtr,
900                            ubi_btActionRtn EachNode,
901                            void           *UserData )
902   /* ------------------------------------------------------------------------ **
903    * Traverse a tree in sorted order (non-recursively).  At each node, call
904    * (*EachNode)(), passing a pointer to the current node, and UserData as the
905    * second parameter.
906    *  Input:   RootPtr  -  a pointer to an ubi_btRoot structure that indicates
907    *                       the tree to be traversed.
908    *           EachNode -  a pointer to a function to be called at each node
909    *                       as the node is visited.
910    *           UserData -  a generic pointer that may point to anything that
911    *                       you choose.
912    *  Output:  A boolean value.  FALSE if the tree is empty, otherwise TRUE.
913    * ------------------------------------------------------------------------ **
914    */
915   {
916   ubi_btNodePtr p;
917
918   if( !(p = ubi_btFirst( RootPtr->root )) ) return( ubi_trFALSE );
919
920   while( p )
921     {
922     EachNode( p, UserData );
923     p = ubi_btNext( p );
924     }
925   return( ubi_trTRUE );
926   } /* ubi_btTraverse */
927
928 ubi_trBool ubi_btKillTree( ubi_btRootPtr     RootPtr,
929                            ubi_btKillNodeRtn FreeNode )
930   /* ------------------------------------------------------------------------ **
931    * Delete an entire tree (non-recursively) and reinitialize the ubi_btRoot
932    * structure.  Note that this function will return FALSE if either parameter
933    * is NULL.
934    *
935    *  Input:   RootPtr  -  a pointer to an ubi_btRoot structure that indicates
936    *                       the root of the tree to delete.
937    *           FreeNode -  a function that will be called for each node in the
938    *                       tree to deallocate the memory used by the node.
939    *
940    *  Output:  A boolean value.  FALSE if either input parameter was NULL, else
941    *           TRUE.
942    *
943    * ------------------------------------------------------------------------ **
944    */
945   {
946   ubi_btNodePtr p, q;
947
948   if( !(RootPtr) || !(FreeNode) )
949     return( ubi_trFALSE );
950
951   p = ubi_btFirst( RootPtr->root );
952   while( p )
953     {
954     q = p;
955     while( q->Link[ubi_trRIGHT] )
956       q = SubSlide( q->Link[ubi_trRIGHT], ubi_trLEFT );
957     p = q->Link[ubi_trPARENT];
958     if( p )
959       p->Link[ ((p->Link[ubi_trLEFT] == q)?ubi_trLEFT:ubi_trRIGHT) ] = NULL;
960     FreeNode((void *)q);
961     }
962
963   (void)ubi_btInitTree( RootPtr,
964                         RootPtr->cmp,
965                         RootPtr->flags );
966   return( ubi_trTRUE );
967   } /* ubi_btKillTree */
968
969 ubi_btNodePtr ubi_btLeafNode( ubi_btNodePtr leader )
970   /* ------------------------------------------------------------------------ **
971    * Returns a pointer to a leaf node.
972    *
973    *  Input:  leader  - Pointer to a node at which to start the descent.
974    *
975    *  Output: A pointer to a leaf node selected in a somewhat arbitrary
976    *          manner.
977    *
978    *  Notes:  I wrote this function because I was using splay trees as a
979    *          database cache.  The cache had a maximum size on it, and I
980    *          needed a way of choosing a node to sacrifice if the cache
981    *          became full.  In a splay tree, less recently accessed nodes
982    *          tend toward the bottom of the tree, meaning that leaf nodes
983    *          are good candidates for removal.  (I really can't think of
984    *          any other reason to use this function.)
985    *        + In a simple binary tree or an AVL tree, the most recently
986    *          added nodes tend to be nearer the bottom, making this a *bad*
987    *          way to choose which node to remove from the cache.
988    *        + Randomizing the traversal order is probably a good idea.  You
989    *          can improve the randomization of leaf node selection by passing
990    *          in pointers to nodes other than the root node each time.  A
991    *          pointer to any node in the tree will do.  Of course, if you
992    *          pass a pointer to a leaf node you'll get the same thing back.
993    *        + If using a splay tree, splaying the tree will tend to randomize
994    *          things a bit too.  See ubi_SplayTree for more info.
995    *
996    * ------------------------------------------------------------------------ **
997    */
998   {
999   ubi_btNodePtr follower = NULL;
1000   int           whichway = ubi_trLEFT;
1001
1002   while( NULL != leader )
1003     {
1004     /* The next line is a weak attempt at randomizing. */
1005     whichway = ((int)leader & 0x0010) ? whichway : ubi_trRevWay(whichway);
1006     follower = leader;
1007     leader   = leader->Link[ whichway ];
1008     if( NULL == leader )
1009       {
1010       whichway = ubi_trRevWay( whichway );
1011       leader   = follower->Link[ whichway ];
1012       }
1013     }
1014
1015   return( follower );
1016   } /* ubi_btLeafNode */
1017
1018 int ubi_btModuleID( int size, char *list[] )
1019   /* ------------------------------------------------------------------------ **
1020    * Returns a set of strings that identify the module.
1021    *
1022    *  Input:  size  - The number of elements in the array <list>.
1023    *          list  - An array of pointers of type (char *).  This array
1024    *                  should, initially, be empty.  This function will fill
1025    *                  in the array with pointers to strings.
1026    *  Output: The number of elements of <list> that were used.  If this value
1027    *          is less than <size>, the values of the remaining elements are
1028    *          not guaranteed.
1029    *
1030    *  Notes:  Please keep in mind that the pointers returned indicate strings
1031    *          stored in static memory.  Don't free() them, don't write over
1032    *          them, etc.  Just read them.
1033    * ------------------------------------------------------------------------ **
1034    */
1035   {
1036   if( size > 0 )
1037     {
1038     list[0] = ModuleID;
1039     if( size > 1 )
1040       list[1] = NULL;
1041     return( 1 );
1042     }
1043   return( 0 );
1044   } /* ubi_btModuleID */
1045
1046 /* ========================================================================== */