1 /* ========================================================================== **
4 * Copyright (C) 1991-1998 by Christopher R. Hertel
6 * Email: crh@ubiqx.mn.org
7 * -------------------------------------------------------------------------- **
9 * This module implements a simple binary tree.
11 * -------------------------------------------------------------------------- **
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.
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.
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.
27 * -------------------------------------------------------------------------- **
29 * Log: ubi_BinTree.c,v
30 * Revision 4.5 1998/06/04 21:29:27 crh
31 * Upper-cased defined constants (eg UBI_BINTREE_H) in some header files.
32 * This is more "standard", and is what people expect. Weird, eh?
34 * Revision 4.4 1998/06/03 17:42:46 crh
35 * Further fiddling with sys_include.h. It's now in ubi_BinTree.h which is
36 * included by all of the binary tree files.
38 * Reminder: Some of the ubi_tr* macros in ubi_BinTree.h are redefined in
39 * ubi_AVLtree.h and ubi_SplayTree.h. This allows easy swapping
40 * of tree types by simply changing a header. Unfortunately, the
41 * macro redefinitions in ubi_AVLtree.h and ubi_SplayTree.h will
42 * conflict if used together. You must either choose a single tree
43 * type, or use the underlying function calls directly. Compare
44 * the two header files for more information.
46 * Revision 4.3 1998/06/02 01:28:43 crh
47 * Changed ubi_null.h to sys_include.h to make it more generic.
49 * Revision 4.2 1998/05/20 04:32:36 crh
50 * The C file now includes ubi_null.h. See ubi_null.h for more info.
51 * Also, the balance and gender fields of the node were declared as
52 * signed char. As I understand it, at least one SunOS or Solaris
53 * compiler doesn't like "signed char". The declarations were
54 * wrong anyway, so I changed them to simple "char".
56 * Revision 4.1 1998/03/31 06:11:57 crh
57 * Thomas Aglassinger sent E'mail pointing out errors in the
58 * dereferencing of function pointers, and a missing typecast.
61 * Revision 4.0 1998/03/10 03:19:22 crh
62 * Added the AVL field 'balance' to the ubi_btNode structure. This means
63 * that all BinTree modules now use the same basic node structure, which
64 * greatly simplifies the AVL module.
65 * Decided that this was a big enough change to justify a new major revision
66 * number. 3.0 was an error, so we're at 4.0.
68 * Revision 2.6 1998/01/24 06:27:46 crh
69 * Added ubi_trCount() macro.
71 * Revision 2.5 1997/12/23 03:56:29 crh
72 * In this version, all constants & macros defined in the header file have
73 * the ubi_tr prefix. Also cleaned up anything that gcc complained about
74 * when run with '-pedantic -fsyntax-only -Wall'.
76 * Revision 2.4 1997/07/26 04:11:10 crh
77 * + Just to be annoying I changed ubi_TRUE and ubi_FALSE to ubi_trTRUE
79 * + There is now a type ubi_trBool to go with ubi_trTRUE and ubi_trFALSE.
80 * + There used to be something called "ubi_TypeDefs.h". I got rid of it.
81 * + Added function ubi_btLeafNode().
83 * Revision 2.3 1997/06/03 05:16:17 crh
84 * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid conflicts.
85 * Also changed the interface to function InitTree(). See the comments
86 * for this function for more information.
88 * Revision 2.2 1995/10/03 22:00:07 CRH
91 * Revision 2.1 95/03/09 23:37:10 CRH
92 * Added the ModuleID static string and function. These modules are now
95 * Revision 2.0 95/02/27 22:00:17 CRH
96 * Revision 2.0 of this program includes the following changes:
98 * 1) A fix to a major typo in the RepaceNode() function.
99 * 2) The addition of the static function Border().
100 * 3) The addition of the public functions FirstOf() and LastOf(), which
101 * use Border(). These functions are used with trees that allow
103 * 4) A complete rewrite of the Locate() function. Locate() now accepts
104 * a "comparison" operator.
105 * 5) Overall enhancements to both code and comments.
107 * I decided to give this a new major rev number because the interface has
108 * changed. In particular, there are two new functions, and changes to the
111 * Revision 1.0 93/10/15 22:44:59 CRH
112 * With this revision, I have added a set of #define's that provide a single,
113 * standard API to all existing tree modules. Until now, each of the three
114 * existing modules had a different function and typedef prefix, as follows:
118 * ubi_AVLtree ubi_avl
119 * ubi_SplayTree ubi_spt
121 * To further complicate matters, only those portions of the base module
122 * (ubi_BinTree) that were superceeded in the new module had the new names.
123 * For example, if you were using ubi_SplayTree, the locate function was
124 * called "ubi_sptLocate", but the next and previous functions remained
125 * "ubi_btNext" and "ubi_btPrev".
127 * This was not too terrible if you were familiar with the modules and knew
128 * exactly which tree model you wanted to use. If you wanted to be able to
129 * change modules (for speed comparisons, etc), things could get messy very
132 * So, I have added a set of defined names that get redefined in any of the
133 * descendant modules. To use this standardized interface in your code,
134 * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
135 * "ubi_tr". The "ubi_tr" names will resolve to the correct function or
136 * datatype names for the module that you are using. Just remember to
137 * include the header for that module in your program file. Because these
138 * names are handled by the preprocessor, there is no added run-time
141 * Note that the original names do still exist, and can be used if you wish
142 * to write code directly to a specific module. This should probably only be
143 * done if you are planning to implement a new descendant type, such as
144 * red/black trees. CRH
146 * V0.0 - June, 1991 - Written by Christopher R. Hertel (CRH).
148 * ========================================================================== **
151 #include "ubi_BinTree.h" /* Header for this module. */
153 /* ========================================================================== **
157 static char ModuleID[] = "ubi_BinTree\n\
159 \tDate: 1998/06/04 21:29:27 \n\
162 /* ========================================================================== **
163 * Internal (private) functions.
166 static ubi_btNodePtr qFind( ubi_btCompFunc cmp,
167 ubi_btItemPtr FindMe,
168 register ubi_btNodePtr p )
169 /* ------------------------------------------------------------------------ **
170 * This function performs a non-recursive search of a tree for a node
171 * matching a specific key. It is called "qFind()" because it is
172 * faster that TreeFind (below).
175 * cmp - a pointer to the tree's comparison function.
176 * FindMe - a pointer to the key value for which to search.
177 * p - a pointer to the starting point of the search. <p>
178 * is considered to be the root of a subtree, and only
179 * the subtree will be searched.
182 * A pointer to a node with a key that matches the key indicated by
183 * FindMe, or NULL if no such node was found.
185 * Note: In a tree that allows duplicates, the pointer returned *might
186 * not* point to the (sequentially) first occurance of the
188 * ------------------------------------------------------------------------ **
193 while( p && (( tmp = ubi_trAbNormal((*cmp)(FindMe, p)) ) != ubi_trEQUAL) )
199 static ubi_btNodePtr TreeFind( ubi_btItemPtr findme,
201 ubi_btNodePtr *parentp,
203 ubi_btCompFunc CmpFunc )
204 /* ------------------------------------------------------------------------ **
205 * TreeFind() searches a tree for a given value (findme). It will return a
206 * pointer to the target node, if found, or NULL if the target node was not
209 * TreeFind() also returns, via parameters, a pointer to the parent of the
210 * target node, and a LEFT or RIGHT value indicating which child of the
211 * parent is the target node. *If the target is not found*, then these
212 * values indicate the place at which the target *should be found*. This
213 * is useful when inserting a new node into a tree or searching for nodes
214 * "near" the target node.
216 * The parameters are:
218 * findme - is a pointer to the key information to be searched for.
219 * p - points to the root of the tree to be searched.
220 * parentp - will return a pointer to a pointer to the !parent! of the
221 * target node, which can be especially usefull if the target
223 * gender - returns LEFT or RIGHT to indicate which child of *parentp
225 * CmpFunc - points to the comparison function.
227 * This function is called by ubi_btLocate() and ubi_btInsert().
228 * ------------------------------------------------------------------------ **
231 register ubi_btNodePtr tmp_p = p;
232 ubi_btNodePtr tmp_pp = NULL;
233 char tmp_gender = ubi_trEQUAL;
237 && (ubi_trEQUAL != (tmp_cmp = ubi_trAbNormal((*CmpFunc)(findme, tmp_p)))) )
239 tmp_pp = tmp_p; /* Keep track of previous node. */
240 tmp_gender = (char)tmp_cmp; /* Keep track of sex of child. */
241 tmp_p = tmp_p->Link[tmp_cmp]; /* Go to child. */
243 *parentp = tmp_pp; /* Return results. */
244 *gender = tmp_gender;
248 static void ReplaceNode( ubi_btNodePtr *parent,
249 ubi_btNodePtr oldnode,
250 ubi_btNodePtr newnode )
251 /* ------------------------------------------------------------------------ **
252 * Remove node oldnode from the tree, replacing it with node newnode.
255 * parent - A pointer to he parent pointer of the node to be
256 * replaced. <parent> may point to the Link[] field of
257 * a parent node, or it may indicate the root pointer at
258 * the top of the tree.
259 * oldnode - A pointer to the node that is to be replaced.
260 * newnode - A pointer to the node that is to be installed in the
261 * place of <*oldnode>.
263 * Notes: Don't forget to free oldnode.
264 * Also, this function used to have a really nasty typo
265 * bug. "oldnode" and "newnode" were swapped in the line
267 * ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
269 * ------------------------------------------------------------------------ **
273 register int btNodeSize = sizeof( ubi_btNode );
275 for( i = 0; i < btNodeSize; i++ ) /* Copy node internals to new node. */
276 ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
277 (*parent) = newnode; /* Old node's parent points to new child. */
278 /* Now tell the children about their new step-parent. */
279 if( oldnode->Link[ubi_trLEFT] )
280 (oldnode->Link[ubi_trLEFT])->Link[ubi_trPARENT] = newnode;
281 if( oldnode->Link[ubi_trRIGHT] )
282 (oldnode->Link[ubi_trRIGHT])->Link[ubi_trPARENT] = newnode;
285 static void SwapNodes( ubi_btRootPtr RootPtr,
287 ubi_btNodePtr Node2 )
288 /* ------------------------------------------------------------------------ **
289 * This function swaps two nodes in the tree. Node1 will take the place of
290 * Node2, and Node2 will fill in the space left vacant by Node 1.
293 * RootPtr - pointer to the tree header structure for this tree.
295 * > These are the two nodes which are to be swapped.
299 * This function does a three step swap, using a dummy node as a place
300 * holder. This function is used by ubi_btRemove().
301 * ------------------------------------------------------------------------ **
304 ubi_btNodePtr *Parent;
306 ubi_btNodePtr dummy_p = &dummy;
308 /* Replace Node 1 with the dummy, thus removing Node1 from the tree. */
309 if( Node1->Link[ubi_trPARENT] )
310 Parent = &((Node1->Link[ubi_trPARENT])->Link[(int)(Node1->gender)]);
312 Parent = &(RootPtr->root);
313 ReplaceNode( Parent, Node1, dummy_p );
315 /* Swap Node 1 with Node 2, placing Node 1 back into the tree. */
316 if( Node2->Link[ubi_trPARENT] )
317 Parent = &((Node2->Link[ubi_trPARENT])->Link[(int)(Node2->gender)]);
319 Parent = &(RootPtr->root);
320 ReplaceNode( Parent, Node2, Node1 );
322 /* Swap Node 2 and the dummy, thus placing Node 2 back into the tree. */
323 if( dummy_p->Link[ubi_trPARENT] )
324 Parent = &((dummy_p->Link[ubi_trPARENT])->Link[(int)(dummy_p->gender)]);
326 Parent = &(RootPtr->root);
327 ReplaceNode( Parent, dummy_p, Node2 );
330 /* -------------------------------------------------------------------------- **
331 * These routines allow you to walk through the tree, forwards or backwards.
334 static ubi_btNodePtr SubSlide( register ubi_btNodePtr P,
335 register int whichway )
336 /* ------------------------------------------------------------------------ **
337 * Slide down the side of a subtree.
339 * Given a starting node, this function returns a pointer to the LEFT-, or
340 * RIGHT-most descendent, *or* (if whichway is PARENT) to the tree root.
342 * Input: P - a pointer to a starting place.
343 * whichway - the direction (LEFT, RIGHT, or PARENT) in which to
345 * Output: A pointer to a node that is either the root, or has no
346 * whichway-th child but is within the subtree of P. Note that
347 * the return value may be the same as P. The return value *will
348 * be* NULL if P is NULL.
349 * ------------------------------------------------------------------------ **
352 ubi_btNodePtr Q = NULL;
357 P = P->Link[ whichway ];
362 static ubi_btNodePtr Neighbor( register ubi_btNodePtr P,
363 register int whichway )
364 /* ------------------------------------------------------------------------ **
365 * Given starting point p, return the (key order) next or preceeding node
368 * Input: P - Pointer to our starting place node.
369 * whichway - the direction in which to travel to find the
370 * neighbor, i.e., the RIGHT neighbor or the LEFT
373 * Output: A pointer to the neighboring node, or NULL if P was NULL.
375 * Notes: If whichway is PARENT, the results are unpredictable.
376 * ------------------------------------------------------------------------ **
381 if( P->Link[ whichway ] )
382 return( SubSlide( P->Link[ whichway ], (char)ubi_trRevWay(whichway) ) );
384 while( P->Link[ ubi_trPARENT ] )
386 if( (P->Link[ ubi_trPARENT ])->Link[ whichway ] == P )
387 P = P->Link[ ubi_trPARENT ];
389 return( P->Link[ ubi_trPARENT ] );
395 static ubi_btNodePtr Border( ubi_btRootPtr RootPtr,
396 ubi_btItemPtr FindMe,
399 /* ------------------------------------------------------------------------ **
400 * Given starting point p, which has a key value equal to *FindMe, locate
401 * the first (index order) node with the same key value.
403 * This function is useful in trees that have can have duplicate keys.
404 * For example, consider the following tree:
406 * 2 If <p> points to the root and <whichway> is RIGHT, 3
407 * / \ then the return value will be a pointer to the / \
408 * 2 2 RIGHT child of the root node. The tree on 2 5
409 * / / \ the right shows the order of traversal. / / \
412 * Input: RootPtr - Pointer to the tree root structure.
413 * FindMe - Key value for comparisons.
414 * p - Pointer to the starting-point node.
415 * whichway - the direction in which to travel to find the
416 * neighbor, i.e., the RIGHT neighbor or the LEFT
419 * Output: A pointer to the first (index, or "traversal", order) node with
420 * a Key value that matches *FindMe.
422 * Notes: If whichway is PARENT, or if the tree does not allow duplicate
423 * keys, this function will return <p>.
424 * ------------------------------------------------------------------------ **
427 register ubi_btNodePtr q;
429 /* Exit if there's nothing that can be done. */
430 if( !ubi_trDups_OK( RootPtr ) || (ubi_trPARENT == whichway) )
433 /* First, if needed, move up the tree. We need to get to the root of the
434 * subtree that contains all of the matching nodes.
436 q = p->Link[ubi_trPARENT];
437 while( q && (ubi_trEQUAL == ubi_trAbNormal( (*(RootPtr->cmp))(FindMe, q) )) )
440 q = p->Link[ubi_trPARENT];
443 /* Next, move back down in the "whichway" direction. */
444 q = p->Link[whichway];
447 q = qFind( RootPtr->cmp, FindMe, q );
451 q = p->Link[whichway];
458 /* ========================================================================== **
459 * Exported utilities.
462 long ubi_btSgn( register long x )
463 /* ------------------------------------------------------------------------ **
464 * Return the sign of x; {negative,zero,positive} ==> {-1, 0, 1}.
466 * Input: x - a signed long integer value.
468 * Output: the "sign" of x, represented as follows:
470 * 0 == zero (no sign)
473 * Note: This utility is provided in order to facilitate the conversion
474 * of C comparison function return values into BinTree direction
475 * values: {LEFT, PARENT, EQUAL}. It is INCORPORATED into the
476 * ubi_trAbNormal() conversion macro!
478 * ------------------------------------------------------------------------ **
481 return( (x)?((x>0)?(1):(-1)):(0) );
484 ubi_btNodePtr ubi_btInitNode( ubi_btNodePtr NodePtr )
485 /* ------------------------------------------------------------------------ **
486 * Initialize a tree node.
488 * Input: a pointer to a ubi_btNode structure to be initialized.
489 * Output: a pointer to the initialized ubi_btNode structure (ie. the
490 * same as the input pointer).
491 * ------------------------------------------------------------------------ **
494 NodePtr->Link[ ubi_trLEFT ] = NULL;
495 NodePtr->Link[ ubi_trPARENT ] = NULL;
496 NodePtr->Link[ ubi_trRIGHT ] = NULL;
497 NodePtr->gender = ubi_trEQUAL;
498 NodePtr->balance = ubi_trEQUAL;
500 } /* ubi_btInitNode */
502 ubi_btRootPtr ubi_btInitTree( ubi_btRootPtr RootPtr,
503 ubi_btCompFunc CompFunc,
505 /* ------------------------------------------------------------------------ **
506 * Initialize the fields of a Tree Root header structure.
508 * Input: RootPtr - a pointer to an ubi_btRoot structure to be
510 * CompFunc - a pointer to a comparison function that will be used
511 * whenever nodes in the tree must be compared against
513 * Flags - One bytes worth of flags. Flags include
514 * ubi_trOVERWRITE and ubi_trDUPKEY. See the header
515 * file for more info.
517 * Output: a pointer to the initialized ubi_btRoot structure (ie. the
518 * same value as RootPtr).
520 * Note: The interface to this function has changed from that of
521 * previous versions. The <Flags> parameter replaces two
522 * boolean parameters that had the same basic effect.
524 * ------------------------------------------------------------------------ **
529 RootPtr->root = NULL;
531 RootPtr->cmp = CompFunc;
532 RootPtr->flags = (Flags & ubi_trDUPKEY) ? ubi_trDUPKEY : Flags;
533 } /* There are only two supported flags, and they are
534 * mutually exclusive. ubi_trDUPKEY takes precedence
535 * over ubi_trOVERWRITE.
538 } /* ubi_btInitTree */
540 ubi_trBool ubi_btInsert( ubi_btRootPtr RootPtr,
541 ubi_btNodePtr NewNode,
542 ubi_btItemPtr ItemPtr,
543 ubi_btNodePtr *OldNode )
544 /* ------------------------------------------------------------------------ **
545 * This function uses a non-recursive algorithm to add a new element to the
548 * Input: RootPtr - a pointer to the ubi_btRoot structure that indicates
549 * the root of the tree to which NewNode is to be added.
550 * NewNode - a pointer to an ubi_btNode structure that is NOT
552 * ItemPtr - A pointer to the sort key that is stored within
553 * *NewNode. ItemPtr MUST point to information stored
554 * in *NewNode or an EXACT DUPLICATE. The key data
555 * indicated by ItemPtr is used to place the new node
557 * OldNode - a pointer to an ubi_btNodePtr. When searching
558 * the tree, a duplicate node may be found. If
559 * duplicates are allowed, then the new node will
560 * be simply placed into the tree. If duplicates
561 * are not allowed, however, then one of two things
563 * 1) if overwritting *is not* allowed, this
564 * function will return FALSE (indicating that
565 * the new node could not be inserted), and
566 * *OldNode will point to the duplicate that is
568 * 2) if overwritting *is* allowed, then this
569 * function will swap **OldNode for *NewNode.
570 * In this case, *OldNode will point to the node
571 * that was removed (thus allowing you to free
573 * ** If you are using overwrite mode, ALWAYS **
574 * ** check the return value of this parameter! **
575 * Note: You may pass NULL in this parameter, the
576 * function knows how to cope. If you do this,
577 * however, there will be no way to return a
578 * pointer to an old (ie. replaced) node (which is
579 * a problem if you are using overwrite mode).
581 * Output: a boolean value indicating success or failure. The function
582 * will return FALSE if the node could not be added to the tree.
583 * Such failure will only occur if duplicates are not allowed,
584 * nodes cannot be overwritten, AND a duplicate key was found
586 * ------------------------------------------------------------------------ **
589 ubi_btNodePtr OtherP,
593 if( !(OldNode) ) /* If they didn't give us a pointer, supply our own. */
596 (void)ubi_btInitNode( NewNode ); /* Init the new node's BinTree fields. */
598 /* Find a place for the new node. */
599 *OldNode = TreeFind(ItemPtr, (RootPtr->root), &parent, &tmp, (RootPtr->cmp));
601 /* Now add the node to the tree... */
602 if (!(*OldNode)) /* The easy one: we have a space for a new node! */
605 RootPtr->root = NewNode;
608 parent->Link[(int)tmp] = NewNode;
609 NewNode->Link[ubi_trPARENT] = parent;
610 NewNode->gender = tmp;
613 return( ubi_trTRUE );
616 /* If we reach this point, we know that a duplicate node exists. This
617 * section adds the node to the tree if duplicate keys are allowed.
619 if( ubi_trDups_OK(RootPtr) ) /* Key exists, add duplicate */
629 if( tmp == ubi_trEQUAL )
631 q = q->Link[(int)tmp];
633 tmp = ubi_trAbNormal( (*(RootPtr->cmp))(ItemPtr, q) );
635 parent->Link[(int)tmp] = NewNode;
636 NewNode->Link[ubi_trPARENT] = parent;
637 NewNode->gender = tmp;
639 return( ubi_trTRUE );
642 /* If we get to *this* point, we know that we are not allowed to have
643 * duplicate nodes, but our node keys match, so... may we replace the
646 if( ubi_trOvwt_OK(RootPtr) ) /* Key exists, we replace */
649 ReplaceNode( &(RootPtr->root), *OldNode, NewNode );
651 ReplaceNode( &(parent->Link[(int)((*OldNode)->gender)]),
653 return( ubi_trTRUE );
656 return( ubi_trFALSE ); /* Failure: could not replace an existing node. */
659 ubi_btNodePtr ubi_btRemove( ubi_btRootPtr RootPtr,
660 ubi_btNodePtr DeadNode )
661 /* ------------------------------------------------------------------------ **
662 * This function removes the indicated node from the tree.
664 * Input: RootPtr - A pointer to the header of the tree that contains
665 * the node to be removed.
666 * DeadNode - A pointer to the node that will be removed.
668 * Output: This function returns a pointer to the node that was removed
669 * from the tree (ie. the same as DeadNode).
671 * Note: The node MUST be in the tree indicated by RootPtr. If not,
672 * strange and evil things will happen to your trees.
673 * ------------------------------------------------------------------------ **
680 /* if the node has both left and right subtrees, then we have to swap
681 * it with another node. The other node we choose will be the Prev()ious
682 * node, which is garunteed to have no RIGHT child.
684 if( (DeadNode->Link[ubi_trLEFT]) && (DeadNode->Link[ubi_trRIGHT]) )
685 SwapNodes( RootPtr, DeadNode, ubi_btPrev( DeadNode ) );
687 /* The parent of the node to be deleted may be another node, or it may be
688 * the root of the tree. Since we're not sure, it's best just to have
689 * a pointer to the parent pointer, whatever it is.
691 if (DeadNode->Link[ubi_trPARENT])
692 parentp = &((DeadNode->Link[ubi_trPARENT])->Link[(int)(DeadNode->gender)]);
694 parentp = &( RootPtr->root );
696 /* Now link the parent to the only grand-child and patch up the gender. */
697 tmp = ((DeadNode->Link[ubi_trLEFT])?ubi_trLEFT:ubi_trRIGHT);
699 p = (DeadNode->Link[tmp]);
702 p->Link[ubi_trPARENT] = DeadNode->Link[ubi_trPARENT];
703 p->gender = DeadNode->gender;
707 /* Finished, reduce the node count and return. */
712 ubi_btNodePtr ubi_btLocate( ubi_btRootPtr RootPtr,
713 ubi_btItemPtr FindMe,
714 ubi_trCompOps CompOp )
715 /* ------------------------------------------------------------------------ **
716 * The purpose of ubi_btLocate() is to find a node or set of nodes given
717 * a target value and a "comparison operator". The Locate() function is
718 * more flexible and (in the case of trees that may contain dupicate keys)
719 * more precise than the ubi_btFind() function. The latter is faster,
720 * but it only searches for exact matches and, if the tree contains
721 * duplicates, Find() may return a pointer to any one of the duplicate-
725 * RootPtr - A pointer to the header of the tree to be searched.
726 * FindMe - An ubi_btItemPtr that indicates the key for which to
728 * CompOp - One of the following:
729 * CompOp Return a pointer to the node with
730 * ------ ---------------------------------
731 * ubi_trLT - the last key value that is less
733 * ubi_trLE - the first key matching FindMe, or
734 * the last key that is less than
736 * ubi_trEQ - the first key matching FindMe.
737 * ubi_trGE - the first key matching FindMe, or the
738 * first key greater than FindMe.
739 * ubi_trGT - the first key greater than FindMe.
741 * A pointer to the node matching the criteria listed above under
742 * CompOp, or NULL if no node matched the criteria.
745 * In the case of trees with duplicate keys, Locate() will behave as
749 * Keys: 1 2 2 2 3 3 3 3 3 4 4 Keys: 1 1 2 2 2 4 4 5 5 5 6
753 * That is, when returning a pointer to a node with a key that is LESS
754 * THAN the target key (FindMe), Locate() will return a pointer to the
755 * LAST matching node.
756 * When returning a pointer to a node with a key that is GREATER
757 * THAN the target key (FindMe), Locate() will return a pointer to the
758 * FIRST matching node.
760 * See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
761 * ------------------------------------------------------------------------ **
764 register ubi_btNodePtr p;
765 ubi_btNodePtr parent;
768 /* Start by searching for a matching node. */
769 p = TreeFind( FindMe,
775 if( p ) /* If we have found a match, we can resolve as follows: */
779 case ubi_trLT: /* It's just a jump to the left... */
780 p = Border( RootPtr, FindMe, p, ubi_trLEFT );
781 return( Neighbor( p, ubi_trLEFT ) );
782 case ubi_trGT: /* ...and then a jump to the right. */
783 p = Border( RootPtr, FindMe, p, ubi_trRIGHT );
784 return( Neighbor( p, ubi_trRIGHT ) );
786 p = Border( RootPtr, FindMe, p, ubi_trLEFT );
791 /* Else, no match. */
792 if( ubi_trEQ == CompOp ) /* If we were looking for an exact match... */
793 return( NULL ); /* ...forget it. */
795 /* We can still return a valid result for GT, GE, LE, and LT.
796 * <parent> points to a node with a value that is either just before or
797 * just after the target value.
798 * Remaining possibilities are LT and GT (including LE & GE).
800 if( (ubi_trLT == CompOp) || (ubi_trLE == CompOp) )
801 return( (ubi_trLEFT == whichkid) ? Neighbor( parent, whichkid ) : parent );
803 return( (ubi_trRIGHT == whichkid) ? Neighbor( parent, whichkid ) : parent );
806 ubi_btNodePtr ubi_btFind( ubi_btRootPtr RootPtr,
807 ubi_btItemPtr FindMe )
808 /* ------------------------------------------------------------------------ **
809 * This function performs a non-recursive search of a tree for any node
810 * matching a specific key.
813 * RootPtr - a pointer to the header of the tree to be searched.
814 * FindMe - a pointer to the key value for which to search.
817 * A pointer to a node with a key that matches the key indicated by
818 * FindMe, or NULL if no such node was found.
820 * Note: In a tree that allows duplicates, the pointer returned *might
821 * not* point to the (sequentially) first occurance of the
822 * desired key. In such a tree, it may be more useful to use
824 * ------------------------------------------------------------------------ **
827 return( qFind( RootPtr->cmp, FindMe, RootPtr->root ) );
830 ubi_btNodePtr ubi_btNext( ubi_btNodePtr P )
831 /* ------------------------------------------------------------------------ **
832 * Given the node indicated by P, find the (sorted order) Next node in the
834 * Input: P - a pointer to a node that exists in a binary tree.
835 * Output: A pointer to the "next" node in the tree, or NULL if P pointed
836 * to the "last" node in the tree or was NULL.
837 * ------------------------------------------------------------------------ **
840 return( Neighbor( P, ubi_trRIGHT ) );
843 ubi_btNodePtr ubi_btPrev( ubi_btNodePtr P )
844 /* ------------------------------------------------------------------------ **
845 * Given the node indicated by P, find the (sorted order) Previous node in
847 * Input: P - a pointer to a node that exists in a binary tree.
848 * Output: A pointer to the "previous" node in the tree, or NULL if P
849 * pointed to the "first" node in the tree or was NULL.
850 * ------------------------------------------------------------------------ **
853 return( Neighbor( P, ubi_trLEFT ) );
856 ubi_btNodePtr ubi_btFirst( ubi_btNodePtr P )
857 /* ------------------------------------------------------------------------ **
858 * Given the node indicated by P, find the (sorted order) First node in the
859 * subtree of which *P is the root.
860 * Input: P - a pointer to a node that exists in a binary tree.
861 * Output: A pointer to the "first" node in a subtree that has *P as its
862 * root. This function will return NULL only if P is NULL.
863 * Note: In general, you will be passing in the value of the root field
864 * of an ubi_btRoot structure.
865 * ------------------------------------------------------------------------ **
868 return( SubSlide( P, ubi_trLEFT ) );
871 ubi_btNodePtr ubi_btLast( ubi_btNodePtr P )
872 /* ------------------------------------------------------------------------ **
873 * Given the node indicated by P, find the (sorted order) Last node in the
874 * subtree of which *P is the root.
875 * Input: P - a pointer to a node that exists in a binary tree.
876 * Output: A pointer to the "last" node in a subtree that has *P as its
877 * root. This function will return NULL only if P is NULL.
878 * Note: In general, you will be passing in the value of the root field
879 * of an ubi_btRoot structure.
880 * ------------------------------------------------------------------------ **
883 return( SubSlide( P, ubi_trRIGHT ) );
886 ubi_btNodePtr ubi_btFirstOf( ubi_btRootPtr RootPtr,
887 ubi_btItemPtr MatchMe,
889 /* ------------------------------------------------------------------------ **
890 * Given a tree that a allows duplicate keys, and a pointer to a node in
891 * the tree, this function will return a pointer to the first (traversal
892 * order) node with the same key value.
894 * Input: RootPtr - A pointer to the root of the tree.
895 * MatchMe - A pointer to the key value. This should probably
896 * point to the key within node *p.
897 * p - A pointer to a node in the tree.
898 * Output: A pointer to the first node in the set of nodes with keys
900 * Notes: Node *p MUST be in the set of nodes with keys matching
901 * <FindMe>. If not, this function will return NULL.
902 * ------------------------------------------------------------------------ **
905 /* If our starting point is invalid, return NULL. */
906 if( !p || ubi_trAbNormal( (*(RootPtr->cmp))( MatchMe, p ) != ubi_trEQUAL ) )
908 return( Border( RootPtr, MatchMe, p, ubi_trLEFT ) );
909 } /* ubi_btFirstOf */
911 ubi_btNodePtr ubi_btLastOf( ubi_btRootPtr RootPtr,
912 ubi_btItemPtr MatchMe,
914 /* ------------------------------------------------------------------------ **
915 * Given a tree that a allows duplicate keys, and a pointer to a node in
916 * the tree, this function will return a pointer to the last (traversal
917 * order) node with the same key value.
919 * Input: RootPtr - A pointer to the root of the tree.
920 * MatchMe - A pointer to the key value. This should probably
921 * point to the key within node *p.
922 * p - A pointer to a node in the tree.
923 * Output: A pointer to the last node in the set of nodes with keys
925 * Notes: Node *p MUST be in the set of nodes with keys matching
926 * <FindMe>. If not, this function will return NULL.
927 * ------------------------------------------------------------------------ **
930 /* If our starting point is invalid, return NULL. */
931 if( !p || ubi_trAbNormal( (*(RootPtr->cmp))( MatchMe, p ) != ubi_trEQUAL ) )
933 return( Border( RootPtr, MatchMe, p, ubi_trRIGHT ) );
936 ubi_trBool ubi_btTraverse( ubi_btRootPtr RootPtr,
937 ubi_btActionRtn EachNode,
939 /* ------------------------------------------------------------------------ **
940 * Traverse a tree in sorted order (non-recursively). At each node, call
941 * (*EachNode)(), passing a pointer to the current node, and UserData as the
943 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
944 * the tree to be traversed.
945 * EachNode - a pointer to a function to be called at each node
946 * as the node is visited.
947 * UserData - a generic pointer that may point to anything that
949 * Output: A boolean value. FALSE if the tree is empty, otherwise TRUE.
950 * ------------------------------------------------------------------------ **
955 if( !(p = ubi_btFirst( RootPtr->root )) ) return( ubi_trFALSE );
959 (*EachNode)( p, UserData );
962 return( ubi_trTRUE );
963 } /* ubi_btTraverse */
965 ubi_trBool ubi_btKillTree( ubi_btRootPtr RootPtr,
966 ubi_btKillNodeRtn FreeNode )
967 /* ------------------------------------------------------------------------ **
968 * Delete an entire tree (non-recursively) and reinitialize the ubi_btRoot
969 * structure. Note that this function will return FALSE if either parameter
972 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
973 * the root of the tree to delete.
974 * FreeNode - a function that will be called for each node in the
975 * tree to deallocate the memory used by the node.
977 * Output: A boolean value. FALSE if either input parameter was NULL, else
980 * ------------------------------------------------------------------------ **
985 if( !(RootPtr) || !(FreeNode) )
986 return( ubi_trFALSE );
988 p = ubi_btFirst( RootPtr->root );
992 while( q->Link[ubi_trRIGHT] )
993 q = SubSlide( q->Link[ubi_trRIGHT], ubi_trLEFT );
994 p = q->Link[ubi_trPARENT];
996 p->Link[ ((p->Link[ubi_trLEFT] == q)?ubi_trLEFT:ubi_trRIGHT) ] = NULL;
997 (*FreeNode)((void *)q);
1000 (void)ubi_btInitTree( RootPtr,
1003 return( ubi_trTRUE );
1004 } /* ubi_btKillTree */
1006 ubi_btNodePtr ubi_btLeafNode( ubi_btNodePtr leader )
1007 /* ------------------------------------------------------------------------ **
1008 * Returns a pointer to a leaf node.
1010 * Input: leader - Pointer to a node at which to start the descent.
1012 * Output: A pointer to a leaf node selected in a somewhat arbitrary
1015 * Notes: I wrote this function because I was using splay trees as a
1016 * database cache. The cache had a maximum size on it, and I
1017 * needed a way of choosing a node to sacrifice if the cache
1018 * became full. In a splay tree, less recently accessed nodes
1019 * tend toward the bottom of the tree, meaning that leaf nodes
1020 * are good candidates for removal. (I really can't think of
1021 * any other reason to use this function.)
1022 * + In a simple binary tree or an AVL tree, the most recently
1023 * added nodes tend to be nearer the bottom, making this a *bad*
1024 * way to choose which node to remove from the cache.
1025 * + Randomizing the traversal order is probably a good idea. You
1026 * can improve the randomization of leaf node selection by passing
1027 * in pointers to nodes other than the root node each time. A
1028 * pointer to any node in the tree will do. Of course, if you
1029 * pass a pointer to a leaf node you'll get the same thing back.
1031 * ------------------------------------------------------------------------ **
1034 ubi_btNodePtr follower = NULL;
1035 int whichway = ubi_trLEFT;
1037 while( NULL != leader )
1040 leader = follower->Link[ whichway ];
1041 if( NULL == leader )
1043 whichway = ubi_trRevWay( whichway );
1044 leader = follower->Link[ whichway ];
1049 } /* ubi_btLeafNode */
1051 int ubi_btModuleID( int size, char *list[] )
1052 /* ------------------------------------------------------------------------ **
1053 * Returns a set of strings that identify the module.
1055 * Input: size - The number of elements in the array <list>.
1056 * list - An array of pointers of type (char *). This array
1057 * should, initially, be empty. This function will fill
1058 * in the array with pointers to strings.
1059 * Output: The number of elements of <list> that were used. If this value
1060 * is less than <size>, the values of the remaining elements are
1063 * Notes: Please keep in mind that the pointers returned indicate strings
1064 * stored in static memory. Don't free() them, don't write over
1065 * them, etc. Just read them.
1066 * ------------------------------------------------------------------------ **
1077 } /* ubi_btModuleID */
1080 /* ========================================================================== */