1 /* ========================================================================== **
4 * Copyright (C) 1991-1997 by Christopher R. Hertel
6 * Email: crh@ubiqx.mn.org
7 * -------------------------------------------------------------------------- **
9 * ubi_BinTree manages a simple binary tree. Nothing fancy here. No height
10 * balancing, no restructuring. Still, a good tool for creating short, low-
11 * overhead sorted lists of things that need to be found in a hurry.
13 * In addition, this module provides a good basis for creating other types
14 * of binary tree handling modules.
16 * -------------------------------------------------------------------------- **
18 * This library is free software; you can redistribute it and/or
19 * modify it under the terms of the GNU Library General Public
20 * License as published by the Free Software Foundation; either
21 * version 2 of the License, or (at your option) any later version.
23 * This library is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 * Library General Public License for more details.
28 * You should have received a copy of the GNU Library General Public
29 * License along with this library; if not, write to the Free
30 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 * -------------------------------------------------------------------------- **
34 * $Log: ubi_BinTree.c,v $
35 * Revision 1.1 1997/10/09 04:09:52 crh
36 * This is my library of lists and trees. My hope is to replace all of the
37 * hard coded linked lists that are currently used in Samba with calls to
38 * these modules. This should make the code simpler, smaller, and (I hope)
39 * faster. The tree code, in particular, should speed up processing where
40 * large lists are involved.
44 * Revision 2.4 1997/07/26 04:11:10 crh
45 * + Just to be annoying I changed ubi_TRUE and ubi_FALSE to ubi_trTRUE
47 * + There is now a type ubi_trBool to go with ubi_trTRUE and ubi_trFALSE.
48 * + There used to be something called "ubi_TypeDefs.h". I got rid of it.
49 * + Added function ubi_btLeafNode().
51 * Revision 2.3 1997/06/03 05:16:17 crh
52 * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid conflicts.
53 * Also changed the interface to function InitTree(). See the comments
54 * for this function for more information.
56 * Revision 2.2 1995/10/03 22:00:07 CRH
59 * Revision 2.1 95/03/09 23:37:10 CRH
60 * Added the ModuleID static string and function. These modules are now
63 * Revision 2.0 95/02/27 22:00:17 CRH
64 * Revision 2.0 of this program includes the following changes:
66 * 1) A fix to a major typo in the RepaceNode() function.
67 * 2) The addition of the static function Border().
68 * 3) The addition of the public functions FirstOf() and LastOf(), which
69 * use Border(). These functions are used with trees that allow
71 * 4) A complete rewrite of the Locate() function. Locate() now accepts
72 * a "comparison" operator.
73 * 5) Overall enhancements to both code and comments.
75 * I decided to give this a new major rev number because the interface has
76 * changed. In particular, there are two new functions, and changes to the
79 * Revision 1.0 93/10/15 22:44:59 CRH
80 * With this revision, I have added a set of #define's that provide a single,
81 * standard API to all existing tree modules. Until now, each of the three
82 * existing modules had a different function and typedef prefix, as follows:
87 * ubi_SplayTree ubi_spt
89 * To further complicate matters, only those portions of the base module
90 * (ubi_BinTree) that were superceeded in the new module had the new names.
91 * For example, if you were using ubi_AVLtree, the AVL node structure was
92 * named "ubi_avlNode", but the root structure was still "ubi_btRoot". Using
93 * SplayTree, the locate function was called "ubi_sptLocate", but the next
94 * and previous functions remained "ubi_btNext" and "ubi_btPrev".
96 * This was not too terrible if you were familiar with the modules and knew
97 * exactly which tree model you wanted to use. If you wanted to be able to
98 * change modules (for speed comparisons, etc), things could get messy very
101 * So, I have added a set of defined names that get redefined in any of the
102 * descendant modules. To use this standardized interface in your code,
103 * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
104 * "ubi_tr". The "ubi_tr" names will resolve to the correct function or
105 * datatype names for the module that you are using. Just remember to
106 * include the header for that module in your program file. Because these
107 * names are handled by the preprocessor, there is no added run-time
110 * Note that the original names do still exist, and can be used if you wish
111 * to write code directly to a specific module. This should probably only be
112 * done if you are planning to implement a new descendant type, such as
113 * red/black trees. CRH
115 * V0.0 - June, 1991 - Written by Christopher R. Hertel (CRH).
117 * ========================================================================== **
120 #include "ubi_BinTree.h" /* Header for this module */
121 #include <stdlib.h> /* Standard C definitions. */
123 /* ========================================================================== **
127 static char ModuleID[] = "ubi_BinTree\n\
128 \t$Revision: 1.1 $\n\
129 \t$Date: 1997/10/09 04:09:52 $\n\
132 /* ========================================================================== **
133 * Internal (private) functions.
136 static ubi_btNodePtr qFind( ubi_btCompFunc cmp,
137 ubi_btItemPtr FindMe,
138 register ubi_btNodePtr p )
139 /* ------------------------------------------------------------------------ **
140 * This function performs a non-recursive search of a tree for a node
141 * matching a specific key. It is called "qFind()" because it is
142 * faster that TreeFind (below).
145 * cmp - a pointer to the tree's comparison function.
146 * FindMe - a pointer to the key value for which to search.
147 * p - a pointer to the starting point of the search. <p>
148 * is considered to be the root of a subtree, and only
149 * the subtree will be searched.
152 * A pointer to a node with a key that matches the key indicated by
153 * FindMe, or NULL if no such node was found.
155 * Note: In a tree that allows duplicates, the pointer returned *might
156 * not* point to the (sequentially) first occurance of the
158 * ------------------------------------------------------------------------ **
163 while( p && (( tmp = AbNormal((*cmp)(FindMe, p)) ) != EQUAL) )
169 static ubi_btNodePtr TreeFind( ubi_btItemPtr findme,
171 ubi_btNodePtr *parentp,
173 ubi_btCompFunc CmpFunc )
174 /* ------------------------------------------------------------------------ **
175 * TreeFind() searches a tree for a given value (findme). It will return a
176 * pointer to the target node, if found, or NULL if the target node was not
179 * TreeFind() also returns, via parameters, a pointer to the parent of the
180 * target node, and a LEFT or RIGHT value indicating which child of the
181 * parent is the target node. *If the target is not found*, then these
182 * values indicate the place at which the target *should be found*. This
183 * is useful when inserting a new node into a tree or searching for nodes
184 * "near" the target node.
186 * The parameters are:
188 * findme - is a pointer to the key information to be searched for.
189 * p - points to the root of the tree to be searched.
190 * parentp - will return a pointer to a pointer to the !parent! of the
191 * target node, which can be especially usefull if the target
193 * gender - returns LEFT or RIGHT to indicate which child of *parentp
195 * CmpFunc - points to the comparison function.
197 * This function is called by ubi_btLocate() and ubi_btInsert().
198 * ------------------------------------------------------------------------ **
201 register ubi_btNodePtr tmp_p = p;
202 ubi_btNodePtr tmp_pp = NULL;
203 char tmp_sex = EQUAL;
206 while( tmp_p && (EQUAL != (tmp_cmp = AbNormal((*CmpFunc)(findme, tmp_p)))) )
208 tmp_pp = tmp_p; /* Keep track of previous node. */
209 tmp_sex = tmp_cmp; /* Keep track of sex of child. */
210 tmp_p = tmp_p->Link[tmp_cmp]; /* Go to child. */
212 *parentp = tmp_pp; /* Return results. */
217 static void ReplaceNode( ubi_btNodePtr *parent,
218 ubi_btNodePtr oldnode,
219 ubi_btNodePtr newnode )
220 /* ------------------------------------------------------------------ *
221 * Remove node oldnode from the tree, replacing it with node newnode.
224 * parent - A pointer to he parent pointer of the node to be
225 * replaced. <parent> may point to the Link[] field of
226 * a parent node, or it may indicate the root pointer at
227 * the top of the tree.
228 * oldnode - A pointer to the node that is to be replaced.
229 * newnode - A pointer to the node that is to be installed in the
230 * place of <*oldnode>.
232 * Notes: Don't forget to free oldnode.
233 * Also, this function used to have a really nasty typo
234 * bug. "oldnode" and "newnode" were swapped in the line
236 * ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
238 * ------------------------------------------------------------------ *
242 register int btNodeSize = sizeof( ubi_btNode );
244 for( i = 0; i < btNodeSize; i++ ) /* Copy node internals to new node. */
245 ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
246 (*parent) = newnode; /* Old node's parent points to new child. */
247 /* Now tell the children about their new step-parent. */
248 if( oldnode->Link[LEFT ] ) (oldnode->Link[LEFT ])->Link[PARENT] = newnode;
249 if( oldnode->Link[RIGHT] ) (oldnode->Link[RIGHT])->Link[PARENT] = newnode;
252 static void SwapNodes( ubi_btRootPtr RootPtr,
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.
260 * RootPtr - pointer to the tree header structure for this tree.
262 * > These are the two nodes which are to be swapped.
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 * ------------------------------------------------------------------------ **
271 ubi_btNodePtr *Parent;
273 ubi_btNodePtr dummy_p = &dummy;
275 /* Replace Node 1 with the dummy, thus removing Node1 from the tree. */
276 if( Node1->Link[PARENT] )
277 Parent = &((Node1->Link[PARENT])->Link[Node1->gender]);
279 Parent = &(RootPtr->root);
280 ReplaceNode( Parent, Node1, dummy_p );
282 /* Swap Node 1 with Node 2, placing Node 1 back into the tree. */
283 if( Node2->Link[PARENT] )
284 Parent = &((Node2->Link[PARENT])->Link[Node2->gender]);
286 Parent = &(RootPtr->root);
287 ReplaceNode( Parent, Node2, Node1 );
289 /* Swap Node 2 and the dummy, thus placing Node 2 back into the tree. */
290 if( dummy_p->Link[PARENT] )
291 Parent = &((dummy_p->Link[PARENT])->Link[dummy_p->gender]);
293 Parent = &(RootPtr->root);
294 ReplaceNode( Parent, dummy_p, Node2 );
297 /* -------------------------------------------------------------------------- **
298 * These routines allow you to walk through the tree, forwards or backwards.
301 static ubi_btNodePtr SubSlide( register ubi_btNodePtr P,
302 register char whichway )
303 /* ------------------------------------------------------------------------ **
304 * Slide down the side of a subtree.
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.
309 * Input: P - a pointer to a starting place.
310 * whichway - the direction (LEFT, RIGHT, or PARENT) in which to
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 * ------------------------------------------------------------------------ **
319 ubi_btNodePtr Q = NULL;
324 P = P->Link[ whichway ];
329 static ubi_btNodePtr Neighbor( register ubi_btNodePtr P,
330 register char whichway )
331 /* ------------------------------------------------------------------------ **
332 * Given starting point p, return the (key order) next or preceeding node
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
340 * Output: A pointer to the neighboring node, or NULL if P was NULL.
342 * Notes: If whichway is PARENT, the results are unpredictable.
343 * ------------------------------------------------------------------------ **
348 if( P->Link[ whichway ] )
349 return( SubSlide( P->Link[ whichway ], (char)RevWay(whichway) ) );
351 while( P->Link[ PARENT ] )
353 if( (P->Link[ PARENT ])->Link[ whichway ] == P )
354 P = P->Link[ PARENT ];
356 return( P->Link[ PARENT ] );
362 static ubi_btNodePtr Border( ubi_btRootPtr RootPtr,
363 ubi_btItemPtr FindMe,
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.
370 * This function is useful in trees that have can have duplicate keys.
371 * For example, consider the following tree:
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. / / \
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
386 * Output: A pointer to the first (index, or "traversal", order) node with
387 * a Key value that matches *FindMe.
389 * Notes: If whichway is PARENT, or if the tree does not allow duplicate
390 * keys, this function will return <p>.
391 * ------------------------------------------------------------------------ **
394 register ubi_btNodePtr q;
396 /* Exit if there's nothing that can be done. */
397 if( !Dups_OK( RootPtr ) || (PARENT == whichway) )
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.
404 while( q && (EQUAL == AbNormal( (*(RootPtr->cmp))(FindMe, q) )) )
410 /* Next, move back down in the "whichway" direction. */
411 q = p->Link[whichway];
414 if( q = qFind( RootPtr->cmp, FindMe, q ) )
417 q = p->Link[whichway];
424 /* ========================================================================== **
425 * Exported utilities.
428 long ubi_btSgn( register long x )
429 /* ------------------------------------------------------------------------ **
430 * Return the sign of x; {negative,zero,positive} ==> {-1, 0, 1}.
432 * Input: x - a signed long integer value.
434 * Output: the "sign" of x, represented as follows:
436 * 0 == zero (no sign)
439 * Note: This utility is provided in order to facilitate the conversion
440 * of C comparison function return values into BinTree direction
441 * values: {LEFT, PARENT, EQUAL}. It is INCORPORATED into the
442 * AbNormal() conversion macro!
444 * ------------------------------------------------------------------------ **
447 return( (x)?((x>0)?(1):(-1)):(0) );
450 ubi_btNodePtr ubi_btInitNode( ubi_btNodePtr NodePtr )
451 /* ------------------------------------------------------------------------ **
452 * Initialize a tree node.
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 * ------------------------------------------------------------------------ **
460 NodePtr->Link[ LEFT ] = NULL;
461 NodePtr->Link[ PARENT ] = NULL;
462 NodePtr->Link[ RIGHT ] = NULL;
463 NodePtr->gender = EQUAL;
465 } /* ubi_btInitNode */
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.
473 * Input: RootPtr - a pointer to an ubi_btRoot structure to be
475 * CompFunc - a pointer to a comparison function that will be used
476 * whenever nodes in the tree must be compared against
478 * Flags - One bytes worth of flags. Flags include
479 * ubi_trOVERWRITE and ubi_trDUPKEY. See the header
480 * file for more info.
482 * Output: a pointer to the initialized ubi_btRoot structure (ie. the
483 * same value as RootPtr).
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.
489 * ------------------------------------------------------------------------ **
494 RootPtr->root = NULL;
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.
503 } /* ubi_btInitTree */
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
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
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
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
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
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
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).
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
551 * ------------------------------------------------------------------------ **
554 ubi_btNodePtr OtherP,
558 if( !(OldNode) ) /* If they didn't give us a pointer, supply our own. */
561 (void)ubi_btInitNode( NewNode ); /* Init the new node's BinTree fields. */
563 /* Find a place for the new node. */
564 *OldNode = TreeFind(ItemPtr, (RootPtr->root), &parent, &tmp, (RootPtr->cmp));
566 /* Now add the node to the tree... */
567 if (!(*OldNode)) /* The easy one: we have a space for a new node! */
570 RootPtr->root = NewNode;
573 parent->Link[tmp] = NewNode;
574 NewNode->Link[PARENT] = parent;
575 NewNode->gender = tmp;
578 return( ubi_trTRUE );
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.
584 if( Dups_OK(RootPtr) ) /* Key exists, add duplicate */
594 if( tmp == EQUAL ) tmp = RIGHT;
597 tmp = AbNormal( (*(RootPtr->cmp))(ItemPtr, q) );
599 parent->Link[tmp] = NewNode;
600 NewNode->Link[PARENT] = parent;
601 NewNode->gender = tmp;
603 return( ubi_trTRUE );
606 /* If we get to *this* point, we know that we are not allowed to have
607 * duplicate nodes, but our node keys match, so... may we replace the
610 if( Ovwt_OK(RootPtr) ) /* Key exists, we replace */
613 ReplaceNode( &(RootPtr->root), *OldNode, NewNode );
615 ReplaceNode( &(parent->Link[(*OldNode)->gender]), *OldNode, NewNode );
616 return( ubi_trTRUE );
619 return( ubi_trFALSE ); /* Failure: could not replace an existing node. */
622 ubi_btNodePtr ubi_btRemove( ubi_btRootPtr RootPtr,
623 ubi_btNodePtr DeadNode )
624 /* ------------------------------------------------------------------------ **
625 * This function removes the indicated node from the tree.
627 * Input: RootPtr - A pointer to the header of the tree that contains
628 * the node to be removed.
629 * DeadNode - A pointer to the node that will be removed.
631 * Output: This function returns a pointer to the node that was removed
632 * from the tree (ie. the same as DeadNode).
634 * Note: The node MUST be in the tree indicated by RootPtr. If not,
635 * strange and evil things will happen to your trees.
636 * ------------------------------------------------------------------------ **
643 /* if the node has both left and right subtrees, then we have to swap
644 * it with another node. The other node we choose will be the Prev()ious
645 * node, which is garunteed to have no RIGHT child.
647 if( (DeadNode->Link[LEFT]) && (DeadNode->Link[RIGHT]) )
648 SwapNodes( RootPtr, DeadNode, ubi_btPrev( DeadNode ) );
650 /* The parent of the node to be deleted may be another node, or it may be
651 * the root of the tree. Since we're not sure, it's best just to have
652 * a pointer to the parent pointer, whatever it is.
654 if (DeadNode->Link[PARENT])
655 parentp = &((DeadNode->Link[PARENT])->Link[DeadNode->gender]);
657 parentp = &( RootPtr->root );
659 /* Now link the parent to the only grand-child and patch up the gender. */
660 tmp = ((DeadNode->Link[LEFT])?LEFT:RIGHT);
662 p = (DeadNode->Link[tmp]);
665 p->Link[PARENT] = DeadNode->Link[PARENT];
666 p->gender = DeadNode->gender;
670 /* Finished, reduce the node count and return. */
675 ubi_btNodePtr ubi_btLocate( ubi_btRootPtr RootPtr,
676 ubi_btItemPtr FindMe,
677 ubi_trCompOps CompOp )
678 /* ------------------------------------------------------------------------ **
679 * The purpose of ubi_btLocate() is to find a node or set of nodes given
680 * a target value and a "comparison operator". The Locate() function is
681 * more flexible and (in the case of trees that may contain dupicate keys)
682 * more precise than the ubi_btFind() function. The latter is faster,
683 * but it only searches for exact matches and, if the tree contains
684 * duplicates, Find() may return a pointer to any one of the duplicate-
688 * RootPtr - A pointer to the header of the tree to be searched.
689 * FindMe - An ubi_btItemPtr that indicates the key for which to
691 * CompOp - One of the following:
692 * CompOp Return a pointer to the node with
693 * ------ ---------------------------------
694 * ubi_trLT - the last key value that is less
696 * ubi_trLE - the first key matching FindMe, or
697 * the last key that is less than
699 * ubi_trEQ - the first key matching FindMe.
700 * ubi_trGE - the first key matching FindMe, or the
701 * first key greater than FindMe.
702 * ubi_trGT - the first key greater than FindMe.
704 * A pointer to the node matching the criteria listed above under
705 * CompOp, or NULL if no node matched the criteria.
708 * In the case of trees with duplicate keys, Locate() will behave as
712 * Keys: 1 2 2 2 3 3 3 3 3 4 4 Keys: 1 1 2 2 2 4 4 5 5 5 6
716 * That is, when returning a pointer to a node with a key that is LESS
717 * THAN the target key (FindMe), Locate() will return a pointer to the
718 * LAST matching node.
719 * When returning a pointer to a node with a key that is GREATER
720 * THAN the target key (FindMe), Locate() will return a pointer to the
721 * FIRST matching node.
723 * See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
724 * ------------------------------------------------------------------------ **
727 register ubi_btNodePtr p;
728 ubi_btNodePtr parent;
731 /* Start by searching for a matching node. */
732 p = TreeFind( FindMe,
738 if( p ) /* If we have found a match, we can resolve as follows: */
742 case ubi_trLT: /* It's just a jump to the left... */
743 p = Border( RootPtr, FindMe, p, LEFT );
744 return( Neighbor( p, LEFT ) );
745 case ubi_trGT: /* ...and then a jump to the right. */
746 p = Border( RootPtr, FindMe, p, RIGHT );
747 return( Neighbor( p, RIGHT ) );
749 p = Border( RootPtr, FindMe, p, LEFT );
753 /* Else, no match. */
754 if( ubi_trEQ == CompOp ) /* If we were looking for an exact match... */
755 return( NULL ); /* ...forget it. */
757 /* We can still return a valid result for GT, GE, LE, and LT.
758 * <parent> points to a node with a value that is either just before or
759 * just after the target value.
760 * Remaining possibilities are LT and GT (including LE & GE).
762 if( (ubi_trLT == CompOp) || (ubi_trLE == CompOp) )
763 return( (LEFT == whichkid) ? Neighbor( parent, whichkid ) : parent );
765 return( (RIGHT == whichkid) ? Neighbor( parent, whichkid ) : parent );
768 ubi_btNodePtr ubi_btFind( ubi_btRootPtr RootPtr,
769 ubi_btItemPtr FindMe )
770 /* ------------------------------------------------------------------------ **
771 * This function performs a non-recursive search of a tree for any node
772 * matching a specific key.
775 * RootPtr - a pointer to the header of the tree to be searched.
776 * FindMe - a pointer to the key value for which to search.
779 * A pointer to a node with a key that matches the key indicated by
780 * FindMe, or NULL if no such node was found.
782 * Note: In a tree that allows duplicates, the pointer returned *might
783 * not* point to the (sequentially) first occurance of the
784 * desired key. In such a tree, it may be more useful to use
786 * ------------------------------------------------------------------------ **
789 return( qFind( RootPtr->cmp, FindMe, RootPtr->root ) );
792 ubi_btNodePtr ubi_btNext( ubi_btNodePtr P )
793 /* ------------------------------------------------------------------------ **
794 * Given the node indicated by P, find the (sorted order) Next node in the
796 * Input: P - a pointer to a node that exists in a binary tree.
797 * Output: A pointer to the "next" node in the tree, or NULL if P pointed
798 * to the "last" node in the tree or was NULL.
799 * ------------------------------------------------------------------------ **
802 return( Neighbor( P, RIGHT ) );
805 ubi_btNodePtr ubi_btPrev( ubi_btNodePtr P )
806 /* ------------------------------------------------------------------------ **
807 * Given the node indicated by P, find the (sorted order) Previous node in
809 * Input: P - a pointer to a node that exists in a binary tree.
810 * Output: A pointer to the "previous" node in the tree, or NULL if P
811 * pointed to the "first" node in the tree or was NULL.
812 * ------------------------------------------------------------------------ **
815 return( Neighbor( P, LEFT ) );
818 ubi_btNodePtr ubi_btFirst( ubi_btNodePtr P )
819 /* ------------------------------------------------------------------------ **
820 * Given the node indicated by P, find the (sorted order) First node in the
821 * subtree of which *P is the root.
822 * Input: P - a pointer to a node that exists in a binary tree.
823 * Output: A pointer to the "first" node in a subtree that has *P as its
824 * root. This function will return NULL only if P is NULL.
825 * Note: In general, you will be passing in the value of the root field
826 * of an ubi_btRoot structure.
827 * ------------------------------------------------------------------------ **
830 return( SubSlide( P, LEFT ) );
833 ubi_btNodePtr ubi_btLast( ubi_btNodePtr P )
834 /* ------------------------------------------------------------------------ **
835 * Given the node indicated by P, find the (sorted order) Last node in the
836 * subtree of which *P is the root.
837 * Input: P - a pointer to a node that exists in a binary tree.
838 * Output: A pointer to the "last" node in a subtree that has *P as its
839 * root. This function will return NULL only if P is NULL.
840 * Note: In general, you will be passing in the value of the root field
841 * of an ubi_btRoot structure.
842 * ------------------------------------------------------------------------ **
845 return( SubSlide( P, RIGHT ) );
848 ubi_btNodePtr ubi_btFirstOf( ubi_btRootPtr RootPtr,
849 ubi_btItemPtr MatchMe,
851 /* ------------------------------------------------------------------------ **
852 * Given a tree that a allows duplicate keys, and a pointer to a node in
853 * the tree, this function will return a pointer to the first (traversal
854 * order) node with the same key value.
856 * Input: RootPtr - A pointer to the root of the tree.
857 * MatchMe - A pointer to the key value. This should probably
858 * point to the key within node *p.
859 * p - A pointer to a node in the tree.
860 * Output: A pointer to the first node in the set of nodes with keys
862 * Notes: Node *p MUST be in the set of nodes with keys matching
863 * <FindMe>. If not, this function will return NULL.
864 * ------------------------------------------------------------------------ **
867 /* If our starting point is invalid, return NULL. */
868 if( !p || AbNormal( (*(RootPtr->cmp))( MatchMe, p ) != EQUAL ) )
870 return( Border( RootPtr, MatchMe, p, LEFT ) );
871 } /* ubi_btFirstOf */
873 ubi_btNodePtr ubi_btLastOf( ubi_btRootPtr RootPtr,
874 ubi_btItemPtr MatchMe,
876 /* ------------------------------------------------------------------------ **
877 * Given a tree that a allows duplicate keys, and a pointer to a node in
878 * the tree, this function will return a pointer to the last (traversal
879 * order) node with the same key value.
881 * Input: RootPtr - A pointer to the root of the tree.
882 * MatchMe - A pointer to the key value. This should probably
883 * point to the key within node *p.
884 * p - A pointer to a node in the tree.
885 * Output: A pointer to the last node in the set of nodes with keys
887 * Notes: Node *p MUST be in the set of nodes with keys matching
888 * <FindMe>. If not, this function will return NULL.
889 * ------------------------------------------------------------------------ **
892 /* If our starting point is invalid, return NULL. */
893 if( !p || AbNormal( (*(RootPtr->cmp))( MatchMe, p ) != EQUAL ) )
895 return( Border( RootPtr, MatchMe, p, RIGHT ) );
898 ubi_trBool ubi_btTraverse( ubi_btRootPtr RootPtr,
899 ubi_btActionRtn EachNode,
901 /* ------------------------------------------------------------------------ **
902 * Traverse a tree in sorted order (non-recursively). At each node, call
903 * (*EachNode)(), passing a pointer to the current node, and UserData as the
905 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
906 * the tree to be traversed.
907 * EachNode - a pointer to a function to be called at each node
908 * as the node is visited.
909 * UserData - a generic pointer that may point to anything that
911 * Output: A boolean value. FALSE if the tree is empty, otherwise TRUE.
912 * ------------------------------------------------------------------------ **
917 if( !(p = ubi_btFirst( RootPtr->root )) ) return( ubi_trFALSE );
921 EachNode( p, UserData );
924 return( ubi_trTRUE );
925 } /* ubi_btTraverse */
927 ubi_trBool ubi_btKillTree( ubi_btRootPtr RootPtr,
928 ubi_btKillNodeRtn FreeNode )
929 /* ------------------------------------------------------------------------ **
930 * Delete an entire tree (non-recursively) and reinitialize the ubi_btRoot
931 * structure. Note that this function will return FALSE if either parameter
934 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
935 * the root of the tree to delete.
936 * FreeNode - a function that will be called for each node in the
937 * tree to deallocate the memory used by the node.
939 * Output: A boolean value. FALSE if either input parameter was NULL, else
942 * ------------------------------------------------------------------------ **
947 if( !(RootPtr) || !(FreeNode) )
948 return( ubi_trFALSE );
950 p = ubi_btFirst( RootPtr->root );
954 while( q->Link[RIGHT] )
955 q = SubSlide( q->Link[RIGHT], LEFT );
958 p->Link[ ((p->Link[LEFT] == q)?LEFT:RIGHT) ] = NULL;
962 (void)ubi_btInitTree( RootPtr,
965 return( ubi_trTRUE );
966 } /* ubi_btKillTree */
968 ubi_btNodePtr ubi_btLeafNode( ubi_btNodePtr leader )
969 /* ------------------------------------------------------------------------ **
970 * Returns a pointer to a leaf node.
972 * Input: leader - Pointer to a node at which to start the descent.
974 * Output: A pointer to a leaf node selected in a somewhat arbitrary
977 * Notes: I wrote this function because I was using splay trees as a
978 * database cache. The cache had a maximum size on it, and I
979 * needed a way of choosing a node to sacrifice if the cache
980 * became full. In a splay tree, less recently accessed nodes
981 * tend toward the bottom of the tree, meaning that leaf nodes
982 * are good candidates for removal. (I really can't think of
983 * any other reason to use this function.)
984 * + In a simple binary tree or an AVL tree, the most recently
985 * added nodes tend to be nearer the bottom, making this a *bad*
986 * way to choose which node to remove from the cache.
987 * + Randomizing the traversal order is probably a good idea. You
988 * can improve the randomization of leaf node selection by passing
989 * in pointers to nodes other than the root node each time. A
990 * pointer to any node in the tree will do. Of course, if you
991 * pass a pointer to a leaf node you'll get the same thing back.
993 * ------------------------------------------------------------------------ **
996 ubi_btNodePtr follower = NULL;
999 while( NULL != leader )
1002 leader = follower->Link[ whichway ];
1003 if( NULL == leader )
1005 whichway = RevWay( whichway );
1006 leader = follower->Link[ whichway ];
1011 } /* ubi_btLeafNode */
1013 int ubi_btModuleID( int size, char *list[] )
1014 /* ------------------------------------------------------------------------ **
1015 * Returns a set of strings that identify the module.
1017 * Input: size - The number of elements in the array <list>.
1018 * list - An array of pointers of type (char *). This array
1019 * should, initially, be empty. This function will fill
1020 * in the array with pointers to strings.
1021 * Output: The number of elements of <list> that were used. If this value
1022 * is less than <size>, the values of the remaining elements are
1025 * Notes: Please keep in mind that the pointers returned indicate strings
1026 * stored in static memory. Don't free() them, don't write over
1027 * them, etc. Just read them.
1028 * ------------------------------------------------------------------------ **
1039 } /* ubi_btModuleID */
1042 /* ========================================================================== */