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/10 14:46:38 crh
36 * This is the ubiqx binary tree and linked list library.
37 * This library is being included as part of the Samba distribution.
40 * Revision 2.4 1997/07/26 04:11:10 crh
41 * + Just to be annoying I changed ubi_TRUE and ubi_FALSE to ubi_trTRUE
43 * + There is now a type ubi_trBool to go with ubi_trTRUE and ubi_trFALSE.
44 * + There used to be something called "ubi_TypeDefs.h". I got rid of it.
45 * + Added function ubi_btLeafNode().
47 * Revision 2.3 1997/06/03 05:16:17 crh
48 * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid conflicts.
49 * Also changed the interface to function InitTree(). See the comments
50 * for this function for more information.
52 * Revision 2.2 1995/10/03 22:00:07 CRH
55 * Revision 2.1 95/03/09 23:37:10 CRH
56 * Added the ModuleID static string and function. These modules are now
59 * Revision 2.0 95/02/27 22:00:17 CRH
60 * Revision 2.0 of this program includes the following changes:
62 * 1) A fix to a major typo in the RepaceNode() function.
63 * 2) The addition of the static function Border().
64 * 3) The addition of the public functions FirstOf() and LastOf(), which
65 * use Border(). These functions are used with trees that allow
67 * 4) A complete rewrite of the Locate() function. Locate() now accepts
68 * a "comparison" operator.
69 * 5) Overall enhancements to both code and comments.
71 * I decided to give this a new major rev number because the interface has
72 * changed. In particular, there are two new functions, and changes to the
75 * Revision 1.0 93/10/15 22:44:59 CRH
76 * With this revision, I have added a set of #define's that provide a single,
77 * standard API to all existing tree modules. Until now, each of the three
78 * existing modules had a different function and typedef prefix, as follows:
83 * ubi_SplayTree ubi_spt
85 * To further complicate matters, only those portions of the base module
86 * (ubi_BinTree) that were superceeded in the new module had the new names.
87 * For example, if you were using ubi_AVLtree, the AVL node structure was
88 * named "ubi_avlNode", but the root structure was still "ubi_btRoot". Using
89 * SplayTree, the locate function was called "ubi_sptLocate", but the next
90 * and previous functions remained "ubi_btNext" and "ubi_btPrev".
92 * This was not too terrible if you were familiar with the modules and knew
93 * exactly which tree model you wanted to use. If you wanted to be able to
94 * change modules (for speed comparisons, etc), things could get messy very
97 * So, I have added a set of defined names that get redefined in any of the
98 * descendant modules. To use this standardized interface in your code,
99 * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
100 * "ubi_tr". The "ubi_tr" names will resolve to the correct function or
101 * datatype names for the module that you are using. Just remember to
102 * include the header for that module in your program file. Because these
103 * names are handled by the preprocessor, there is no added run-time
106 * Note that the original names do still exist, and can be used if you wish
107 * to write code directly to a specific module. This should probably only be
108 * done if you are planning to implement a new descendant type, such as
109 * red/black trees. CRH
111 * V0.0 - June, 1991 - Written by Christopher R. Hertel (CRH).
113 * ========================================================================== **
116 #include "ubi_BinTree.h" /* Header for this module */
117 #include <stdlib.h> /* Standard C definitions. */
119 /* ========================================================================== **
123 static char ModuleID[] = "ubi_BinTree\n\
124 \t$Revision: 1.1 $\n\
125 \t$Date: 1997/10/10 14:46:38 $\n\
128 /* ========================================================================== **
129 * Internal (private) functions.
132 static ubi_btNodePtr qFind( ubi_btCompFunc cmp,
133 ubi_btItemPtr FindMe,
134 register ubi_btNodePtr p )
135 /* ------------------------------------------------------------------------ **
136 * This function performs a non-recursive search of a tree for a node
137 * matching a specific key. It is called "qFind()" because it is
138 * faster that TreeFind (below).
141 * cmp - a pointer to the tree's comparison function.
142 * FindMe - a pointer to the key value for which to search.
143 * p - a pointer to the starting point of the search. <p>
144 * is considered to be the root of a subtree, and only
145 * the subtree will be searched.
148 * A pointer to a node with a key that matches the key indicated by
149 * FindMe, or NULL if no such node was found.
151 * Note: In a tree that allows duplicates, the pointer returned *might
152 * not* point to the (sequentially) first occurance of the
154 * ------------------------------------------------------------------------ **
159 while( p && (( tmp = AbNormal((*cmp)(FindMe, p)) ) != EQUAL) )
165 static ubi_btNodePtr TreeFind( ubi_btItemPtr findme,
167 ubi_btNodePtr *parentp,
169 ubi_btCompFunc CmpFunc )
170 /* ------------------------------------------------------------------------ **
171 * TreeFind() searches a tree for a given value (findme). It will return a
172 * pointer to the target node, if found, or NULL if the target node was not
175 * TreeFind() also returns, via parameters, a pointer to the parent of the
176 * target node, and a LEFT or RIGHT value indicating which child of the
177 * parent is the target node. *If the target is not found*, then these
178 * values indicate the place at which the target *should be found*. This
179 * is useful when inserting a new node into a tree or searching for nodes
180 * "near" the target node.
182 * The parameters are:
184 * findme - is a pointer to the key information to be searched for.
185 * p - points to the root of the tree to be searched.
186 * parentp - will return a pointer to a pointer to the !parent! of the
187 * target node, which can be especially usefull if the target
189 * gender - returns LEFT or RIGHT to indicate which child of *parentp
191 * CmpFunc - points to the comparison function.
193 * This function is called by ubi_btLocate() and ubi_btInsert().
194 * ------------------------------------------------------------------------ **
197 register ubi_btNodePtr tmp_p = p;
198 ubi_btNodePtr tmp_pp = NULL;
199 char tmp_sex = EQUAL;
202 while( tmp_p && (EQUAL != (tmp_cmp = AbNormal((*CmpFunc)(findme, tmp_p)))) )
204 tmp_pp = tmp_p; /* Keep track of previous node. */
205 tmp_sex = tmp_cmp; /* Keep track of sex of child. */
206 tmp_p = tmp_p->Link[tmp_cmp]; /* Go to child. */
208 *parentp = tmp_pp; /* Return results. */
213 static void ReplaceNode( ubi_btNodePtr *parent,
214 ubi_btNodePtr oldnode,
215 ubi_btNodePtr newnode )
216 /* ------------------------------------------------------------------ *
217 * Remove node oldnode from the tree, replacing it with node newnode.
220 * parent - A pointer to he parent pointer of the node to be
221 * replaced. <parent> may point to the Link[] field of
222 * a parent node, or it may indicate the root pointer at
223 * the top of the tree.
224 * oldnode - A pointer to the node that is to be replaced.
225 * newnode - A pointer to the node that is to be installed in the
226 * place of <*oldnode>.
228 * Notes: Don't forget to free oldnode.
229 * Also, this function used to have a really nasty typo
230 * bug. "oldnode" and "newnode" were swapped in the line
232 * ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
234 * ------------------------------------------------------------------ *
238 register int btNodeSize = sizeof( ubi_btNode );
240 for( i = 0; i < btNodeSize; i++ ) /* Copy node internals to new node. */
241 ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
242 (*parent) = newnode; /* Old node's parent points to new child. */
243 /* Now tell the children about their new step-parent. */
244 if( oldnode->Link[LEFT ] ) (oldnode->Link[LEFT ])->Link[PARENT] = newnode;
245 if( oldnode->Link[RIGHT] ) (oldnode->Link[RIGHT])->Link[PARENT] = newnode;
248 static void SwapNodes( ubi_btRootPtr RootPtr,
250 ubi_btNodePtr Node2 )
251 /* ------------------------------------------------------------------------ **
252 * This function swaps two nodes in the tree. Node1 will take the place of
253 * Node2, and Node2 will fill in the space left vacant by Node 1.
256 * RootPtr - pointer to the tree header structure for this tree.
258 * > These are the two nodes which are to be swapped.
262 * This function does a three step swap, using a dummy node as a place
263 * holder. This function is used by ubi_btRemove().
264 * ------------------------------------------------------------------------ **
267 ubi_btNodePtr *Parent;
269 ubi_btNodePtr dummy_p = &dummy;
271 /* Replace Node 1 with the dummy, thus removing Node1 from the tree. */
272 if( Node1->Link[PARENT] )
273 Parent = &((Node1->Link[PARENT])->Link[Node1->gender]);
275 Parent = &(RootPtr->root);
276 ReplaceNode( Parent, Node1, dummy_p );
278 /* Swap Node 1 with Node 2, placing Node 1 back into the tree. */
279 if( Node2->Link[PARENT] )
280 Parent = &((Node2->Link[PARENT])->Link[Node2->gender]);
282 Parent = &(RootPtr->root);
283 ReplaceNode( Parent, Node2, Node1 );
285 /* Swap Node 2 and the dummy, thus placing Node 2 back into the tree. */
286 if( dummy_p->Link[PARENT] )
287 Parent = &((dummy_p->Link[PARENT])->Link[dummy_p->gender]);
289 Parent = &(RootPtr->root);
290 ReplaceNode( Parent, dummy_p, Node2 );
293 /* -------------------------------------------------------------------------- **
294 * These routines allow you to walk through the tree, forwards or backwards.
297 static ubi_btNodePtr SubSlide( register ubi_btNodePtr P,
298 register char whichway )
299 /* ------------------------------------------------------------------------ **
300 * Slide down the side of a subtree.
302 * Given a starting node, this function returns a pointer to the LEFT-, or
303 * RIGHT-most descendent, *or* (if whichway is PARENT) to the tree root.
305 * Input: P - a pointer to a starting place.
306 * whichway - the direction (LEFT, RIGHT, or PARENT) in which to
308 * Output: A pointer to a node that is either the root, or has no
309 * whichway-th child but is within the subtree of P. Note that
310 * the return value may be the same as P. The return value *will
311 * be* NULL if P is NULL.
312 * ------------------------------------------------------------------------ **
315 ubi_btNodePtr Q = NULL;
320 P = P->Link[ whichway ];
325 static ubi_btNodePtr Neighbor( register ubi_btNodePtr P,
326 register char whichway )
327 /* ------------------------------------------------------------------------ **
328 * Given starting point p, return the (key order) next or preceeding node
331 * Input: P - Pointer to our starting place node.
332 * whichway - the direction in which to travel to find the
333 * neighbor, i.e., the RIGHT neighbor or the LEFT
336 * Output: A pointer to the neighboring node, or NULL if P was NULL.
338 * Notes: If whichway is PARENT, the results are unpredictable.
339 * ------------------------------------------------------------------------ **
344 if( P->Link[ whichway ] )
345 return( SubSlide( P->Link[ whichway ], (char)RevWay(whichway) ) );
347 while( P->Link[ PARENT ] )
349 if( (P->Link[ PARENT ])->Link[ whichway ] == P )
350 P = P->Link[ PARENT ];
352 return( P->Link[ PARENT ] );
358 static ubi_btNodePtr Border( ubi_btRootPtr RootPtr,
359 ubi_btItemPtr FindMe,
362 /* ------------------------------------------------------------------------ **
363 * Given starting point p, which has a key value equal to *FindMe, locate
364 * the first (index order) node with the same key value.
366 * This function is useful in trees that have can have duplicate keys.
367 * For example, consider the following tree:
369 * 2 If <p> points to the root and <whichway> is RIGHT, 3
370 * / \ then the return value will be a pointer to the / \
371 * 2 2 RIGHT child of the root node. The tree on 2 5
372 * / / \ the right shows the order of traversal. / / \
375 * Input: RootPtr - Pointer to the tree root structure.
376 * FindMe - Key value for comparisons.
377 * p - Pointer to the starting-point node.
378 * whichway - the direction in which to travel to find the
379 * neighbor, i.e., the RIGHT neighbor or the LEFT
382 * Output: A pointer to the first (index, or "traversal", order) node with
383 * a Key value that matches *FindMe.
385 * Notes: If whichway is PARENT, or if the tree does not allow duplicate
386 * keys, this function will return <p>.
387 * ------------------------------------------------------------------------ **
390 register ubi_btNodePtr q;
392 /* Exit if there's nothing that can be done. */
393 if( !Dups_OK( RootPtr ) || (PARENT == whichway) )
396 /* First, if needed, move up the tree. We need to get to the root of the
397 * subtree that contains all of the matching nodes.
400 while( q && (EQUAL == AbNormal( (*(RootPtr->cmp))(FindMe, q) )) )
406 /* Next, move back down in the "whichway" direction. */
407 q = p->Link[whichway];
410 if( q = qFind( RootPtr->cmp, FindMe, q ) )
413 q = p->Link[whichway];
420 /* ========================================================================== **
421 * Exported utilities.
424 long ubi_btSgn( register long x )
425 /* ------------------------------------------------------------------------ **
426 * Return the sign of x; {negative,zero,positive} ==> {-1, 0, 1}.
428 * Input: x - a signed long integer value.
430 * Output: the "sign" of x, represented as follows:
432 * 0 == zero (no sign)
435 * Note: This utility is provided in order to facilitate the conversion
436 * of C comparison function return values into BinTree direction
437 * values: {LEFT, PARENT, EQUAL}. It is INCORPORATED into the
438 * AbNormal() conversion macro!
440 * ------------------------------------------------------------------------ **
443 return( (x)?((x>0)?(1):(-1)):(0) );
446 ubi_btNodePtr ubi_btInitNode( ubi_btNodePtr NodePtr )
447 /* ------------------------------------------------------------------------ **
448 * Initialize a tree node.
450 * Input: a pointer to a ubi_btNode structure to be initialized.
451 * Output: a pointer to the initialized ubi_btNode structure (ie. the
452 * same as the input pointer).
453 * ------------------------------------------------------------------------ **
456 NodePtr->Link[ LEFT ] = NULL;
457 NodePtr->Link[ PARENT ] = NULL;
458 NodePtr->Link[ RIGHT ] = NULL;
459 NodePtr->gender = EQUAL;
461 } /* ubi_btInitNode */
463 ubi_btRootPtr ubi_btInitTree( ubi_btRootPtr RootPtr,
464 ubi_btCompFunc CompFunc,
465 unsigned char Flags )
466 /* ------------------------------------------------------------------------ **
467 * Initialize the fields of a Tree Root header structure.
469 * Input: RootPtr - a pointer to an ubi_btRoot structure to be
471 * CompFunc - a pointer to a comparison function that will be used
472 * whenever nodes in the tree must be compared against
474 * Flags - One bytes worth of flags. Flags include
475 * ubi_trOVERWRITE and ubi_trDUPKEY. See the header
476 * file for more info.
478 * Output: a pointer to the initialized ubi_btRoot structure (ie. the
479 * same value as RootPtr).
481 * Note: The interface to this function has changed from that of
482 * previous versions. The <Flags> parameter replaces two
483 * boolean parameters that had the same basic effect.
485 * ------------------------------------------------------------------------ **
490 RootPtr->root = NULL;
492 RootPtr->cmp = CompFunc;
493 RootPtr->flags = (Flags & ubi_trDUPKEY) ? ubi_trDUPKEY : Flags;
494 } /* There are only two supported flags, and they are
495 * mutually exclusive. ubi_trDUPKEY takes precedence
496 * over ubi_trOVERWRITE.
499 } /* ubi_btInitTree */
501 ubi_trBool ubi_btInsert( ubi_btRootPtr RootPtr,
502 ubi_btNodePtr NewNode,
503 ubi_btItemPtr ItemPtr,
504 ubi_btNodePtr *OldNode )
505 /* ------------------------------------------------------------------------ **
506 * This function uses a non-recursive algorithm to add a new element to the
509 * Input: RootPtr - a pointer to the ubi_btRoot structure that indicates
510 * the root of the tree to which NewNode is to be added.
511 * NewNode - a pointer to an ubi_btNode structure that is NOT
513 * ItemPtr - A pointer to the sort key that is stored within
514 * *NewNode. ItemPtr MUST point to information stored
515 * in *NewNode or an EXACT DUPLICATE. The key data
516 * indicated by ItemPtr is used to place the new node
518 * OldNode - a pointer to an ubi_btNodePtr. When searching
519 * the tree, a duplicate node may be found. If
520 * duplicates are allowed, then the new node will
521 * be simply placed into the tree. If duplicates
522 * are not allowed, however, then one of two things
524 * 1) if overwritting *is not* allowed, this
525 * function will return FALSE (indicating that
526 * the new node could not be inserted), and
527 * *OldNode will point to the duplicate that is
529 * 2) if overwritting *is* allowed, then this
530 * function will swap **OldNode for *NewNode.
531 * In this case, *OldNode will point to the node
532 * that was removed (thus allowing you to free
534 * ** If you are using overwrite mode, ALWAYS **
535 * ** check the return value of this parameter! **
536 * Note: You may pass NULL in this parameter, the
537 * function knows how to cope. If you do this,
538 * however, there will be no way to return a
539 * pointer to an old (ie. replaced) node (which is
540 * a problem if you are using overwrite mode).
542 * Output: a boolean value indicating success or failure. The function
543 * will return FALSE if the node could not be added to the tree.
544 * Such failure will only occur if duplicates are not allowed,
545 * nodes cannot be overwritten, AND a duplicate key was found
547 * ------------------------------------------------------------------------ **
550 ubi_btNodePtr OtherP,
554 if( !(OldNode) ) /* If they didn't give us a pointer, supply our own. */
557 (void)ubi_btInitNode( NewNode ); /* Init the new node's BinTree fields. */
559 /* Find a place for the new node. */
560 *OldNode = TreeFind(ItemPtr, (RootPtr->root), &parent, &tmp, (RootPtr->cmp));
562 /* Now add the node to the tree... */
563 if (!(*OldNode)) /* The easy one: we have a space for a new node! */
566 RootPtr->root = NewNode;
569 parent->Link[tmp] = NewNode;
570 NewNode->Link[PARENT] = parent;
571 NewNode->gender = tmp;
574 return( ubi_trTRUE );
577 /* If we reach this point, we know that a duplicate node exists. This
578 * section adds the node to the tree if duplicate keys are allowed.
580 if( Dups_OK(RootPtr) ) /* Key exists, add duplicate */
590 if( tmp == EQUAL ) tmp = RIGHT;
593 tmp = AbNormal( (*(RootPtr->cmp))(ItemPtr, q) );
595 parent->Link[tmp] = NewNode;
596 NewNode->Link[PARENT] = parent;
597 NewNode->gender = tmp;
599 return( ubi_trTRUE );
602 /* If we get to *this* point, we know that we are not allowed to have
603 * duplicate nodes, but our node keys match, so... may we replace the
606 if( Ovwt_OK(RootPtr) ) /* Key exists, we replace */
609 ReplaceNode( &(RootPtr->root), *OldNode, NewNode );
611 ReplaceNode( &(parent->Link[(*OldNode)->gender]), *OldNode, NewNode );
612 return( ubi_trTRUE );
615 return( ubi_trFALSE ); /* Failure: could not replace an existing node. */
618 ubi_btNodePtr ubi_btRemove( ubi_btRootPtr RootPtr,
619 ubi_btNodePtr DeadNode )
620 /* ------------------------------------------------------------------------ **
621 * This function removes the indicated node from the tree.
623 * Input: RootPtr - A pointer to the header of the tree that contains
624 * the node to be removed.
625 * DeadNode - A pointer to the node that will be removed.
627 * Output: This function returns a pointer to the node that was removed
628 * from the tree (ie. the same as DeadNode).
630 * Note: The node MUST be in the tree indicated by RootPtr. If not,
631 * strange and evil things will happen to your trees.
632 * ------------------------------------------------------------------------ **
639 /* if the node has both left and right subtrees, then we have to swap
640 * it with another node. The other node we choose will be the Prev()ious
641 * node, which is garunteed to have no RIGHT child.
643 if( (DeadNode->Link[LEFT]) && (DeadNode->Link[RIGHT]) )
644 SwapNodes( RootPtr, DeadNode, ubi_btPrev( DeadNode ) );
646 /* The parent of the node to be deleted may be another node, or it may be
647 * the root of the tree. Since we're not sure, it's best just to have
648 * a pointer to the parent pointer, whatever it is.
650 if (DeadNode->Link[PARENT])
651 parentp = &((DeadNode->Link[PARENT])->Link[DeadNode->gender]);
653 parentp = &( RootPtr->root );
655 /* Now link the parent to the only grand-child and patch up the gender. */
656 tmp = ((DeadNode->Link[LEFT])?LEFT:RIGHT);
658 p = (DeadNode->Link[tmp]);
661 p->Link[PARENT] = DeadNode->Link[PARENT];
662 p->gender = DeadNode->gender;
666 /* Finished, reduce the node count and return. */
671 ubi_btNodePtr ubi_btLocate( ubi_btRootPtr RootPtr,
672 ubi_btItemPtr FindMe,
673 ubi_trCompOps CompOp )
674 /* ------------------------------------------------------------------------ **
675 * The purpose of ubi_btLocate() is to find a node or set of nodes given
676 * a target value and a "comparison operator". The Locate() function is
677 * more flexible and (in the case of trees that may contain dupicate keys)
678 * more precise than the ubi_btFind() function. The latter is faster,
679 * but it only searches for exact matches and, if the tree contains
680 * duplicates, Find() may return a pointer to any one of the duplicate-
684 * RootPtr - A pointer to the header of the tree to be searched.
685 * FindMe - An ubi_btItemPtr that indicates the key for which to
687 * CompOp - One of the following:
688 * CompOp Return a pointer to the node with
689 * ------ ---------------------------------
690 * ubi_trLT - the last key value that is less
692 * ubi_trLE - the first key matching FindMe, or
693 * the last key that is less than
695 * ubi_trEQ - the first key matching FindMe.
696 * ubi_trGE - the first key matching FindMe, or the
697 * first key greater than FindMe.
698 * ubi_trGT - the first key greater than FindMe.
700 * A pointer to the node matching the criteria listed above under
701 * CompOp, or NULL if no node matched the criteria.
704 * In the case of trees with duplicate keys, Locate() will behave as
708 * Keys: 1 2 2 2 3 3 3 3 3 4 4 Keys: 1 1 2 2 2 4 4 5 5 5 6
712 * That is, when returning a pointer to a node with a key that is LESS
713 * THAN the target key (FindMe), Locate() will return a pointer to the
714 * LAST matching node.
715 * When returning a pointer to a node with a key that is GREATER
716 * THAN the target key (FindMe), Locate() will return a pointer to the
717 * FIRST matching node.
719 * See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
720 * ------------------------------------------------------------------------ **
723 register ubi_btNodePtr p;
724 ubi_btNodePtr parent;
727 /* Start by searching for a matching node. */
728 p = TreeFind( FindMe,
734 if( p ) /* If we have found a match, we can resolve as follows: */
738 case ubi_trLT: /* It's just a jump to the left... */
739 p = Border( RootPtr, FindMe, p, LEFT );
740 return( Neighbor( p, LEFT ) );
741 case ubi_trGT: /* ...and then a jump to the right. */
742 p = Border( RootPtr, FindMe, p, RIGHT );
743 return( Neighbor( p, RIGHT ) );
745 p = Border( RootPtr, FindMe, p, LEFT );
749 /* Else, no match. */
750 if( ubi_trEQ == CompOp ) /* If we were looking for an exact match... */
751 return( NULL ); /* ...forget it. */
753 /* We can still return a valid result for GT, GE, LE, and LT.
754 * <parent> points to a node with a value that is either just before or
755 * just after the target value.
756 * Remaining possibilities are LT and GT (including LE & GE).
758 if( (ubi_trLT == CompOp) || (ubi_trLE == CompOp) )
759 return( (LEFT == whichkid) ? Neighbor( parent, whichkid ) : parent );
761 return( (RIGHT == whichkid) ? Neighbor( parent, whichkid ) : parent );
764 ubi_btNodePtr ubi_btFind( ubi_btRootPtr RootPtr,
765 ubi_btItemPtr FindMe )
766 /* ------------------------------------------------------------------------ **
767 * This function performs a non-recursive search of a tree for any node
768 * matching a specific key.
771 * RootPtr - a pointer to the header of the tree to be searched.
772 * FindMe - a pointer to the key value for which to search.
775 * A pointer to a node with a key that matches the key indicated by
776 * FindMe, or NULL if no such node was found.
778 * Note: In a tree that allows duplicates, the pointer returned *might
779 * not* point to the (sequentially) first occurance of the
780 * desired key. In such a tree, it may be more useful to use
782 * ------------------------------------------------------------------------ **
785 return( qFind( RootPtr->cmp, FindMe, RootPtr->root ) );
788 ubi_btNodePtr ubi_btNext( ubi_btNodePtr P )
789 /* ------------------------------------------------------------------------ **
790 * Given the node indicated by P, find the (sorted order) Next node in the
792 * Input: P - a pointer to a node that exists in a binary tree.
793 * Output: A pointer to the "next" node in the tree, or NULL if P pointed
794 * to the "last" node in the tree or was NULL.
795 * ------------------------------------------------------------------------ **
798 return( Neighbor( P, RIGHT ) );
801 ubi_btNodePtr ubi_btPrev( ubi_btNodePtr P )
802 /* ------------------------------------------------------------------------ **
803 * Given the node indicated by P, find the (sorted order) Previous node in
805 * Input: P - a pointer to a node that exists in a binary tree.
806 * Output: A pointer to the "previous" node in the tree, or NULL if P
807 * pointed to the "first" node in the tree or was NULL.
808 * ------------------------------------------------------------------------ **
811 return( Neighbor( P, LEFT ) );
814 ubi_btNodePtr ubi_btFirst( ubi_btNodePtr P )
815 /* ------------------------------------------------------------------------ **
816 * Given the node indicated by P, find the (sorted order) First node in the
817 * subtree of which *P is the root.
818 * Input: P - a pointer to a node that exists in a binary tree.
819 * Output: A pointer to the "first" node in a subtree that has *P as its
820 * root. This function will return NULL only if P is NULL.
821 * Note: In general, you will be passing in the value of the root field
822 * of an ubi_btRoot structure.
823 * ------------------------------------------------------------------------ **
826 return( SubSlide( P, LEFT ) );
829 ubi_btNodePtr ubi_btLast( ubi_btNodePtr P )
830 /* ------------------------------------------------------------------------ **
831 * Given the node indicated by P, find the (sorted order) Last node in the
832 * subtree of which *P is the root.
833 * Input: P - a pointer to a node that exists in a binary tree.
834 * Output: A pointer to the "last" node in a subtree that has *P as its
835 * root. This function will return NULL only if P is NULL.
836 * Note: In general, you will be passing in the value of the root field
837 * of an ubi_btRoot structure.
838 * ------------------------------------------------------------------------ **
841 return( SubSlide( P, RIGHT ) );
844 ubi_btNodePtr ubi_btFirstOf( ubi_btRootPtr RootPtr,
845 ubi_btItemPtr MatchMe,
847 /* ------------------------------------------------------------------------ **
848 * Given a tree that a allows duplicate keys, and a pointer to a node in
849 * the tree, this function will return a pointer to the first (traversal
850 * order) node with the same key value.
852 * Input: RootPtr - A pointer to the root of the tree.
853 * MatchMe - A pointer to the key value. This should probably
854 * point to the key within node *p.
855 * p - A pointer to a node in the tree.
856 * Output: A pointer to the first node in the set of nodes with keys
858 * Notes: Node *p MUST be in the set of nodes with keys matching
859 * <FindMe>. If not, this function will return NULL.
860 * ------------------------------------------------------------------------ **
863 /* If our starting point is invalid, return NULL. */
864 if( !p || AbNormal( (*(RootPtr->cmp))( MatchMe, p ) != EQUAL ) )
866 return( Border( RootPtr, MatchMe, p, LEFT ) );
867 } /* ubi_btFirstOf */
869 ubi_btNodePtr ubi_btLastOf( ubi_btRootPtr RootPtr,
870 ubi_btItemPtr MatchMe,
872 /* ------------------------------------------------------------------------ **
873 * Given a tree that a allows duplicate keys, and a pointer to a node in
874 * the tree, this function will return a pointer to the last (traversal
875 * order) node with the same key value.
877 * Input: RootPtr - A pointer to the root of the tree.
878 * MatchMe - A pointer to the key value. This should probably
879 * point to the key within node *p.
880 * p - A pointer to a node in the tree.
881 * Output: A pointer to the last node in the set of nodes with keys
883 * Notes: Node *p MUST be in the set of nodes with keys matching
884 * <FindMe>. If not, this function will return NULL.
885 * ------------------------------------------------------------------------ **
888 /* If our starting point is invalid, return NULL. */
889 if( !p || AbNormal( (*(RootPtr->cmp))( MatchMe, p ) != EQUAL ) )
891 return( Border( RootPtr, MatchMe, p, RIGHT ) );
894 ubi_trBool ubi_btTraverse( ubi_btRootPtr RootPtr,
895 ubi_btActionRtn EachNode,
897 /* ------------------------------------------------------------------------ **
898 * Traverse a tree in sorted order (non-recursively). At each node, call
899 * (*EachNode)(), passing a pointer to the current node, and UserData as the
901 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
902 * the tree to be traversed.
903 * EachNode - a pointer to a function to be called at each node
904 * as the node is visited.
905 * UserData - a generic pointer that may point to anything that
907 * Output: A boolean value. FALSE if the tree is empty, otherwise TRUE.
908 * ------------------------------------------------------------------------ **
913 if( !(p = ubi_btFirst( RootPtr->root )) ) return( ubi_trFALSE );
917 EachNode( p, UserData );
920 return( ubi_trTRUE );
921 } /* ubi_btTraverse */
923 ubi_trBool ubi_btKillTree( ubi_btRootPtr RootPtr,
924 ubi_btKillNodeRtn FreeNode )
925 /* ------------------------------------------------------------------------ **
926 * Delete an entire tree (non-recursively) and reinitialize the ubi_btRoot
927 * structure. Note that this function will return FALSE if either parameter
930 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
931 * the root of the tree to delete.
932 * FreeNode - a function that will be called for each node in the
933 * tree to deallocate the memory used by the node.
935 * Output: A boolean value. FALSE if either input parameter was NULL, else
938 * ------------------------------------------------------------------------ **
943 if( !(RootPtr) || !(FreeNode) )
944 return( ubi_trFALSE );
946 p = ubi_btFirst( RootPtr->root );
950 while( q->Link[RIGHT] )
951 q = SubSlide( q->Link[RIGHT], LEFT );
954 p->Link[ ((p->Link[LEFT] == q)?LEFT:RIGHT) ] = NULL;
958 (void)ubi_btInitTree( RootPtr,
961 return( ubi_trTRUE );
962 } /* ubi_btKillTree */
964 ubi_btNodePtr ubi_btLeafNode( ubi_btNodePtr leader )
965 /* ------------------------------------------------------------------------ **
966 * Returns a pointer to a leaf node.
968 * Input: leader - Pointer to a node at which to start the descent.
970 * Output: A pointer to a leaf node selected in a somewhat arbitrary
973 * Notes: I wrote this function because I was using splay trees as a
974 * database cache. The cache had a maximum size on it, and I
975 * needed a way of choosing a node to sacrifice if the cache
976 * became full. In a splay tree, less recently accessed nodes
977 * tend toward the bottom of the tree, meaning that leaf nodes
978 * are good candidates for removal. (I really can't think of
979 * any other reason to use this function.)
980 * + In a simple binary tree or an AVL tree, the most recently
981 * added nodes tend to be nearer the bottom, making this a *bad*
982 * way to choose which node to remove from the cache.
983 * + Randomizing the traversal order is probably a good idea. You
984 * can improve the randomization of leaf node selection by passing
985 * in pointers to nodes other than the root node each time. A
986 * pointer to any node in the tree will do. Of course, if you
987 * pass a pointer to a leaf node you'll get the same thing back.
989 * ------------------------------------------------------------------------ **
992 ubi_btNodePtr follower = NULL;
995 while( NULL != leader )
998 leader = follower->Link[ whichway ];
1001 whichway = RevWay( whichway );
1002 leader = follower->Link[ whichway ];
1007 } /* ubi_btLeafNode */
1009 int ubi_btModuleID( int size, char *list[] )
1010 /* ------------------------------------------------------------------------ **
1011 * Returns a set of strings that identify the module.
1013 * Input: size - The number of elements in the array <list>.
1014 * list - An array of pointers of type (char *). This array
1015 * should, initially, be empty. This function will fill
1016 * in the array with pointers to strings.
1017 * Output: The number of elements of <list> that were used. If this value
1018 * is less than <size>, the values of the remaining elements are
1021 * Notes: Please keep in mind that the pointers returned indicate strings
1022 * stored in static memory. Don't free() them, don't write over
1023 * them, etc. Just read them.
1024 * ------------------------------------------------------------------------ **
1035 } /* ubi_btModuleID */
1038 /* ========================================================================== */