1 /* ========================================================================== **
4 * Copyright (C) 1991-1997 by Christopher R. Hertel
6 * Email: crh@ubiqx.mn.org
7 * -------------------------------------------------------------------------- **
9 * This module implements simple binary trees.
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 3.0 1997/12/08 06:49:11 crh
31 * This is a new major revision level for all ubiqx binary tree modules.
32 * In previous releases, the ubi_trNode structure looked like this:
34 * typedef struct ubi_btNodeStruct
36 * struct ubi_btNodeStruct *Link[3];
40 * As a result, the pointers were indexed as
42 * Link[0] == Left Child
44 * Link[2] == Right Child
46 * With this release, the node structure changes to:
48 * typedef struct ubi_btNodeStruct
50 * struct ubi_btNodeStruct *leftlink
51 * struct ubi_btNodeStruct *Link[2];
55 * The leftlink field is used as a place holder, and the pointers are now
58 * Link[-1] == Left Child (aka. leftlink)
60 * Link[ 1] == Right Child
62 * which is much nicer. Doing things this way removes the need to shift
63 * values between the two numbering schemes, thus removing one macro,
64 * simplifying another, and getting rid of a whole bunch of increment &
65 * decrement operations.
67 * Revision 2; 1995/02/27 - 1997/12/07 included:
68 * - The addition of the ModuleID static string and ubi_ModuleID() function.
69 * - The addition of the public functions FirstOf() and LastOf(). These
70 * functions are used with trees that allow duplicate keys.
71 * - The addition of the ubi_btLeafNode() function.
72 * - A rewrite of the Locate() function.
73 * - A change to the parameter list in function ubi_btInitTree().
76 * Revision 1; 93/10/15 - 95/02/27:
77 * Revision 1 introduced a set of #define's that provide a single API to all
78 * of the existing tree modules. Each of these modules has a different name
84 * ubi_SplayTree ubi_spt
86 * Only those portions of the base module (ubi_BinTree) that are superceeded
87 * in the descendant module have new names. For example, the AVL node
88 * structure in ubi_AVLtree.h is named "ubi_avlNode", but the root structure
89 * is still "ubi_btRoot". Using SplayTree, the locate function is called
90 * "ubi_sptLocate", but the next and previous functions remained "ubi_btNext"
95 * So, I added a set of defined names that get redefined in any of the
96 * descendant modules. To use this standardized interface in your code,
97 * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
98 * "ubi_tr". The "ubi_tr" names will resolve to the correct function or
99 * datatype names for the module that you are using. Just remember to
100 * include the header for that module in your program file. Because these
101 * names are handled by the preprocessor, there is no added run-time
104 * Note that the original names do still exist, and can be used if you wish
105 * to write code directly to a specific module. This should probably only be
106 * done if you are planning to implement a new descendant type, such as
107 * red/black trees, or if you plan to use two or more specific tree types
108 * in the same piece of code. CRH
110 * V0.0 - June, 1991 - Written by Christopher R. Hertel (CRH).
112 * ========================================================================== **
115 #include "ubi_BinTree.h" /* Header for this module */
116 #include <stdlib.h> /* Standard C definitions. */
118 /* ========================================================================== **
122 static char ModuleID[] = "ubi_BinTree\n\
124 \tDate: 1997/12/08 06:49:11\n\
127 /* ========================================================================== **
128 * Internal (private) functions.
131 static ubi_btNodePtr qFind( ubi_btCompFunc cmp,
132 ubi_btItemPtr FindMe,
133 register ubi_btNodePtr p )
134 /* ------------------------------------------------------------------------ **
135 * This function performs a non-recursive search of a tree for a node
136 * matching a specific key. It is called "qFind()" because it is
137 * (probably a little bit) faster that TreeFind (below).
140 * cmp - a pointer to the tree's comparison function.
141 * FindMe - a pointer to the key value for which to search.
142 * p - a pointer to the starting point of the search. <p>
143 * is considered to be the root of a subtree, and only
144 * the subtree will be searched.
147 * A pointer to a node with a key that matches the key indicated by
148 * FindMe, or NULL if no such node was found.
150 * Note: In a tree that allows duplicates, the pointer returned *might
151 * not* point to the (sequentially) first occurance of the
153 * ------------------------------------------------------------------------ **
158 while( p && (( tmp = ubi_trNormalize((*cmp)(FindMe, p)) ) != ubi_trEQUAL) )
164 static ubi_btNodePtr TreeFind( ubi_btItemPtr findme,
166 ubi_btNodePtr *parentp,
168 ubi_btCompFunc CmpFunc )
169 /* ------------------------------------------------------------------------ **
170 * TreeFind() searches a tree for a given value (findme). It will return a
171 * pointer to the target node, if found, or NULL if the target node was not
174 * TreeFind() also returns, via parameters, a pointer to the parent of the
175 * target node, and a LEFT or RIGHT value indicating which child of the
176 * parent is the target node. *If the target is not found*, then these
177 * values indicate the place at which the target *should be found*. This
178 * is useful when inserting a new node into a tree or searching for nodes
179 * "near" the target node.
181 * The parameters are:
183 * findme - is a pointer to the key information to be searched for.
184 * p - points to the root of the tree to be searched.
185 * parentp - will return a pointer to a pointer to the !parent! of the
186 * target node, which can be especially usefull if the target
188 * gender - returns LEFT or RIGHT to indicate which child of *parentp
190 * CmpFunc - points to the comparison function.
192 * This function is called by ubi_btLocate() and ubi_btInsert().
193 * ------------------------------------------------------------------------ **
196 register ubi_btNodePtr tmp_p = p;
197 ubi_btNodePtr tmp_pp = NULL;
198 signed char tmp_gender = ubi_trEQUAL;
202 && (ubi_trEQUAL != (tmp_cmp = ubi_trNormalize((*CmpFunc)(findme, tmp_p))))
205 tmp_pp = tmp_p; /* Keep track of previous node. */
206 tmp_gender = tmp_cmp; /* Keep track of sex of child. */
207 tmp_p = tmp_p->Link[tmp_cmp]; /* Go to child. */
209 *parentp = tmp_pp; /* Return results. */
210 *gender = tmp_gender;
214 static void ReplaceNode( ubi_btNodePtr *parent,
215 ubi_btNodePtr oldnode,
216 ubi_btNodePtr newnode )
217 /* ------------------------------------------------------------------------ **
218 * Remove node oldnode from the tree, replacing it with node newnode.
221 * parent - A pointer to he parent pointer of the node to be
222 * replaced. <parent> may point to the Link[] field of
223 * a parent node, or it may indicate the root pointer at
224 * the top of the tree.
225 * oldnode - A pointer to the node that is to be replaced.
226 * newnode - A pointer to the node that is to be installed in the
227 * place of <*oldnode>.
229 * Notes: Don't forget to free oldnode.
231 * ------------------------------------------------------------------------ **
235 register int btNodeSize = sizeof( ubi_btNode );
237 for( i = 0; i < btNodeSize; i++ ) /* Copy node internals to new node. */
238 ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
240 /* Old node's parent points to new child. */
243 /* Now tell the children about their new step-parent. */
244 if( oldnode->Link[ubi_trLEFT ] )
245 (oldnode->Link[ubi_trLEFT ])->Link[ubi_trPARENT] = newnode;
247 if( oldnode->Link[ubi_trRIGHT] )
248 (oldnode->Link[ubi_trRIGHT])->Link[ubi_trPARENT] = 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[ubi_trPARENT] )
277 Parent = &((Node1->Link[ubi_trPARENT])->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[ubi_trPARENT] )
284 Parent = &((Node2->Link[ubi_trPARENT])->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[ubi_trPARENT] )
291 Parent = &((dummy_p->Link[ubi_trPARENT])->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 signed 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 signed 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 ], ubi_trRevWay(whichway) ) );
351 while( P->Link[ ubi_trPARENT ] )
353 if( (P->Link[ ubi_trPARENT ])->Link[ whichway ] == P )
354 P = P->Link[ ubi_trPARENT ];
356 return( P->Link[ ubi_trPARENT ] );
362 static ubi_btNodePtr Border( ubi_btRootPtr RootPtr,
363 ubi_btItemPtr FindMe,
365 signed char whichway )
366 /* ------------------------------------------------------------------------ **
367 * Given starting point p, which has a key value equal to *FindMe, locate
368 * the first (index order) node with the same key value.
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( !ubi_trDups_OK( RootPtr ) || (ubi_trPARENT == 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.
403 q = p->Link[ubi_trPARENT];
404 while( q && (ubi_trEQUAL == ubi_trNormalize( (*(RootPtr->cmp))(FindMe, q) )) )
407 q = p->Link[ubi_trPARENT];
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: -1, 0, or 1 representing the "sign" of x 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: {ubi_trLEFT, ubi_trPARENT, ubi_trEQUAL}. It is
442 * incorporated into the ubi_trNormalize() 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[ ubi_trLEFT ] = NULL;
461 NodePtr->Link[ ubi_trPARENT ] = NULL;
462 NodePtr->Link[ ubi_trRIGHT ] = NULL;
463 NodePtr->gender = ubi_trEQUAL;
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[ubi_trPARENT] = 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( ubi_trDups_OK(RootPtr) ) /* Key exists, add duplicate */
594 if( tmp == ubi_trEQUAL )
598 tmp = ubi_trNormalize( (*(RootPtr->cmp))(ItemPtr, q) );
600 parent->Link[tmp] = NewNode;
601 NewNode->Link[ubi_trPARENT] = parent;
602 NewNode->gender = tmp;
604 return( ubi_trTRUE );
607 /* If we get to *this* point, we know that we are not allowed to have
608 * duplicate nodes, but our node keys match, so... may we replace the
611 if( ubi_trOvwt_OK(RootPtr) ) /* Key exists, we replace */
614 ReplaceNode( &(RootPtr->root), *OldNode, NewNode );
616 ReplaceNode( &(parent->Link[(*OldNode)->gender]), *OldNode, NewNode );
617 return( ubi_trTRUE );
620 return( ubi_trFALSE ); /* Failure: could not replace an existing node. */
623 ubi_btNodePtr ubi_btRemove( ubi_btRootPtr RootPtr,
624 ubi_btNodePtr DeadNode )
625 /* ------------------------------------------------------------------------ **
626 * This function removes the indicated node from the tree.
628 * Input: RootPtr - A pointer to the header of the tree that contains
629 * the node to be removed.
630 * DeadNode - A pointer to the node that will be removed.
632 * Output: This function returns a pointer to the node that was removed
633 * from the tree (ie. the same as DeadNode).
635 * Note: The node MUST be in the tree indicated by RootPtr. If not,
636 * strange and evil things will happen to your trees.
637 * ------------------------------------------------------------------------ **
644 /* if the node has both left and right subtrees, then we have to swap
645 * it with another node. The other node we choose will be the Prev()ious
646 * node, which is garunteed to have no RIGHT child.
648 if( (DeadNode->Link[ubi_trLEFT]) && (DeadNode->Link[ubi_trRIGHT]) )
649 SwapNodes( RootPtr, DeadNode, ubi_btPrev( DeadNode ) );
651 /* The parent of the node to be deleted may be another node, or it may be
652 * the root of the tree. Since we're not sure, it's best just to have
653 * a pointer to the parent pointer, whatever it is.
655 if (DeadNode->Link[ubi_trPARENT])
656 parentp = &((DeadNode->Link[ubi_trPARENT])->Link[DeadNode->gender]);
658 parentp = &( RootPtr->root );
660 /* Now link the parent to the only grand-child and patch up the gender. */
661 tmp = ((DeadNode->Link[ubi_trLEFT]) ? ubi_trLEFT : ubi_trRIGHT);
663 p = (DeadNode->Link[tmp]);
666 p->Link[ubi_trPARENT] = DeadNode->Link[ubi_trPARENT];
667 p->gender = DeadNode->gender;
671 /* Finished, reduce the node count and return. */
676 ubi_btNodePtr ubi_btLocate( ubi_btRootPtr RootPtr,
677 ubi_btItemPtr FindMe,
678 ubi_trCompOps CompOp )
679 /* ------------------------------------------------------------------------ **
680 * The purpose of ubi_btLocate() is to find a node or set of nodes given
681 * a target value and a "comparison operator". The Locate() function is
682 * more flexible and (in the case of trees that may contain dupicate keys)
683 * more precise than the ubi_btFind() function. The latter is faster,
684 * but it only searches for exact matches and, if the tree contains
685 * duplicates, Find() may return a pointer to any one of the duplicate-
689 * RootPtr - A pointer to the header of the tree to be searched.
690 * FindMe - An ubi_btItemPtr that indicates the key for which to
692 * CompOp - One of the following:
693 * CompOp Return a pointer to the node with
694 * ------ ---------------------------------
695 * ubi_trLT - the last key value that is less
697 * ubi_trLE - the first key matching FindMe, or
698 * the last key that is less than
700 * ubi_trEQ - the first key matching FindMe.
701 * ubi_trGE - the first key matching FindMe, or the
702 * first key greater than FindMe.
703 * ubi_trGT - the first key greater than FindMe.
705 * A pointer to the node matching the criteria listed above under
706 * CompOp, or NULL if no node matched the criteria.
709 * In the case of trees with duplicate keys, Locate() will behave as
713 * Keys: 1 2 2 2 3 3 3 3 3 4 4 Keys: 1 1 2 2 2 4 4 5 5 5 6
717 * That is, when returning a pointer to a node with a key that is LESS
718 * THAN the target key (FindMe), Locate() will return a pointer to the
719 * LAST matching node.
720 * When returning a pointer to a node with a key that is GREATER
721 * THAN the target key (FindMe), Locate() will return a pointer to the
722 * FIRST matching node.
724 * See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
725 * ------------------------------------------------------------------------ **
728 register ubi_btNodePtr p;
729 ubi_btNodePtr parent;
730 signed char whichkid;
732 /* Start by searching for a matching node. */
733 p = TreeFind( FindMe,
739 if( p ) /* If we have found a match, we can resolve as follows: */
743 case ubi_trLT: /* It's just a jump to the left... */
744 p = Border( RootPtr, FindMe, p, ubi_trLEFT );
745 return( Neighbor( p, ubi_trLEFT ) );
746 case ubi_trGT: /* ...and then a jump to the right. */
747 p = Border( RootPtr, FindMe, p, ubi_trRIGHT );
748 return( Neighbor( p, ubi_trRIGHT ) );
750 p = Border( RootPtr, FindMe, p, ubi_trLEFT );
754 /* Else, no match. */
755 if( ubi_trEQ == CompOp ) /* If we were looking for an exact match... */
756 return( NULL ); /* ...forget it. */
758 /* We can still return a valid result for GT, GE, LE, and LT.
759 * <parent> points to a node with a value that is either just before or
760 * just after the target value.
761 * Remaining possibilities are LT and GT (including LE & GE).
763 if( (ubi_trLT == CompOp) || (ubi_trLE == CompOp) )
764 return( (ubi_trLEFT == whichkid) ? Neighbor( parent, whichkid ) : parent );
766 return( (ubi_trRIGHT == whichkid) ? Neighbor( parent, whichkid ) : parent );
769 ubi_btNodePtr ubi_btFind( ubi_btRootPtr RootPtr,
770 ubi_btItemPtr FindMe )
771 /* ------------------------------------------------------------------------ **
772 * This function performs a non-recursive search of a tree for any node
773 * matching a specific key.
776 * RootPtr - a pointer to the header of the tree to be searched.
777 * FindMe - a pointer to the key value for which to search.
780 * A pointer to a node with a key that matches the key indicated by
781 * FindMe, or NULL if no such node was found.
783 * Note: In a tree that allows duplicates, the pointer returned *might
784 * not* point to the (sequentially) first occurance of the
785 * desired key. In such a tree, it may be more useful to use
787 * ------------------------------------------------------------------------ **
790 return( qFind( RootPtr->cmp, FindMe, RootPtr->root ) );
793 ubi_btNodePtr ubi_btNext( ubi_btNodePtr P )
794 /* ------------------------------------------------------------------------ **
795 * Given the node indicated by P, find the (sorted order) Next node in the
797 * Input: P - a pointer to a node that exists in a binary tree.
798 * Output: A pointer to the "next" node in the tree, or NULL if P pointed
799 * to the "last" node in the tree or was NULL.
800 * ------------------------------------------------------------------------ **
803 return( Neighbor( P, ubi_trRIGHT ) );
806 ubi_btNodePtr ubi_btPrev( ubi_btNodePtr P )
807 /* ------------------------------------------------------------------------ **
808 * Given the node indicated by P, find the (sorted order) Previous node in
810 * Input: P - a pointer to a node that exists in a binary tree.
811 * Output: A pointer to the "previous" node in the tree, or NULL if P
812 * pointed to the "first" node in the tree or was NULL.
813 * ------------------------------------------------------------------------ **
816 return( Neighbor( P, ubi_trLEFT ) );
819 ubi_btNodePtr ubi_btFirst( ubi_btNodePtr P )
820 /* ------------------------------------------------------------------------ **
821 * Given the node indicated by P, find the (sorted order) First node in the
822 * subtree of which *P is the root.
823 * Input: P - a pointer to a node that exists in a binary tree.
824 * Output: A pointer to the "first" node in a subtree that has *P as its
825 * root. This function will return NULL only if P is NULL.
826 * Note: In general, you will be passing in the value of the root field
827 * of an ubi_btRoot structure.
828 * ------------------------------------------------------------------------ **
831 return( SubSlide( P, ubi_trLEFT ) );
834 ubi_btNodePtr ubi_btLast( ubi_btNodePtr P )
835 /* ------------------------------------------------------------------------ **
836 * Given the node indicated by P, find the (sorted order) Last node in the
837 * subtree of which *P is the root.
838 * Input: P - a pointer to a node that exists in a binary tree.
839 * Output: A pointer to the "last" node in a subtree that has *P as its
840 * root. This function will return NULL only if P is NULL.
841 * Note: In general, you will be passing in the value of the root field
842 * of an ubi_btRoot structure.
843 * ------------------------------------------------------------------------ **
846 return( SubSlide( P, ubi_trRIGHT ) );
849 ubi_btNodePtr ubi_btFirstOf( ubi_btRootPtr RootPtr,
850 ubi_btItemPtr MatchMe,
852 /* ------------------------------------------------------------------------ **
853 * Given a tree that a allows duplicate keys, and a pointer to a node in
854 * the tree, this function will return a pointer to the first (traversal
855 * order) node with the same key value.
857 * Input: RootPtr - A pointer to the root of the tree.
858 * MatchMe - A pointer to the key value. This should probably
859 * point to the key within node *p.
860 * p - A pointer to a node in the tree.
861 * Output: A pointer to the first node in the set of nodes with keys
863 * Notes: Node *p MUST be in the set of nodes with keys matching
864 * <FindMe>. If not, this function will return NULL.
865 * ------------------------------------------------------------------------ **
868 /* If our starting point is invalid, return NULL. */
869 if( !p || ubi_trNormalize( (*(RootPtr->cmp))( MatchMe, p ) != ubi_trEQUAL ) )
871 return( Border( RootPtr, MatchMe, p, ubi_trLEFT ) );
872 } /* ubi_btFirstOf */
874 ubi_btNodePtr ubi_btLastOf( ubi_btRootPtr RootPtr,
875 ubi_btItemPtr MatchMe,
877 /* ------------------------------------------------------------------------ **
878 * Given a tree that a allows duplicate keys, and a pointer to a node in
879 * the tree, this function will return a pointer to the last (traversal
880 * order) node with the same key value.
882 * Input: RootPtr - A pointer to the root of the tree.
883 * MatchMe - A pointer to the key value. This should probably
884 * point to the key within node *p.
885 * p - A pointer to a node in the tree.
886 * Output: A pointer to the last node in the set of nodes with keys
888 * Notes: Node *p MUST be in the set of nodes with keys matching
889 * <FindMe>. If not, this function will return NULL.
890 * ------------------------------------------------------------------------ **
893 /* If our starting point is invalid, return NULL. */
894 if( !p || ubi_trNormalize( (*(RootPtr->cmp))( MatchMe, p ) != ubi_trEQUAL ) )
896 return( Border( RootPtr, MatchMe, p, ubi_trRIGHT ) );
899 ubi_trBool ubi_btTraverse( ubi_btRootPtr RootPtr,
900 ubi_btActionRtn EachNode,
902 /* ------------------------------------------------------------------------ **
903 * Traverse a tree in sorted order (non-recursively). At each node, call
904 * (*EachNode)(), passing a pointer to the current node, and UserData as the
906 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
907 * the tree to be traversed.
908 * EachNode - a pointer to a function to be called at each node
909 * as the node is visited.
910 * UserData - a generic pointer that may point to anything that
912 * Output: A boolean value. FALSE if the tree is empty, otherwise TRUE.
913 * ------------------------------------------------------------------------ **
918 if( !(p = ubi_btFirst( RootPtr->root )) ) return( ubi_trFALSE );
922 EachNode( p, UserData );
925 return( ubi_trTRUE );
926 } /* ubi_btTraverse */
928 ubi_trBool ubi_btKillTree( ubi_btRootPtr RootPtr,
929 ubi_btKillNodeRtn FreeNode )
930 /* ------------------------------------------------------------------------ **
931 * Delete an entire tree (non-recursively) and reinitialize the ubi_btRoot
932 * structure. Note that this function will return FALSE if either parameter
935 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
936 * the root of the tree to delete.
937 * FreeNode - a function that will be called for each node in the
938 * tree to deallocate the memory used by the node.
940 * Output: A boolean value. FALSE if either input parameter was NULL, else
943 * ------------------------------------------------------------------------ **
948 if( !(RootPtr) || !(FreeNode) )
949 return( ubi_trFALSE );
951 p = ubi_btFirst( RootPtr->root );
955 while( q->Link[ubi_trRIGHT] )
956 q = SubSlide( q->Link[ubi_trRIGHT], ubi_trLEFT );
957 p = q->Link[ubi_trPARENT];
959 p->Link[ ((p->Link[ubi_trLEFT] == q)?ubi_trLEFT:ubi_trRIGHT) ] = NULL;
963 (void)ubi_btInitTree( RootPtr,
966 return( ubi_trTRUE );
967 } /* ubi_btKillTree */
969 ubi_btNodePtr ubi_btLeafNode( ubi_btNodePtr leader )
970 /* ------------------------------------------------------------------------ **
971 * Returns a pointer to a leaf node.
973 * Input: leader - Pointer to a node at which to start the descent.
975 * Output: A pointer to a leaf node selected in a somewhat arbitrary
978 * Notes: I wrote this function because I was using splay trees as a
979 * database cache. The cache had a maximum size on it, and I
980 * needed a way of choosing a node to sacrifice if the cache
981 * became full. In a splay tree, less recently accessed nodes
982 * tend toward the bottom of the tree, meaning that leaf nodes
983 * are good candidates for removal. (I really can't think of
984 * any other reason to use this function.)
985 * + In a simple binary tree or an AVL tree, the most recently
986 * added nodes tend to be nearer the bottom, making this a *bad*
987 * way to choose which node to remove from the cache.
988 * + Randomizing the traversal order is probably a good idea. You
989 * can improve the randomization of leaf node selection by passing
990 * in pointers to nodes other than the root node each time. A
991 * pointer to any node in the tree will do. Of course, if you
992 * pass a pointer to a leaf node you'll get the same thing back.
993 * + If using a splay tree, splaying the tree will tend to randomize
994 * things a bit too. See ubi_SplayTree for more info.
996 * ------------------------------------------------------------------------ **
999 ubi_btNodePtr follower = NULL;
1000 int whichway = ubi_trLEFT;
1002 while( NULL != leader )
1004 /* The next line is a weak attempt at randomizing. */
1005 whichway = ((int)leader & 0x0010) ? whichway : ubi_trRevWay(whichway);
1007 leader = leader->Link[ whichway ];
1008 if( NULL == leader )
1010 whichway = ubi_trRevWay( whichway );
1011 leader = follower->Link[ whichway ];
1016 } /* ubi_btLeafNode */
1018 int ubi_btModuleID( int size, char *list[] )
1019 /* ------------------------------------------------------------------------ **
1020 * Returns a set of strings that identify the module.
1022 * Input: size - The number of elements in the array <list>.
1023 * list - An array of pointers of type (char *). This array
1024 * should, initially, be empty. This function will fill
1025 * in the array with pointers to strings.
1026 * Output: The number of elements of <list> that were used. If this value
1027 * is less than <size>, the values of the remaining elements are
1030 * Notes: Please keep in mind that the pointers returned indicate strings
1031 * stored in static memory. Don't free() them, don't write over
1032 * them, etc. Just read them.
1033 * ------------------------------------------------------------------------ **
1044 } /* ubi_btModuleID */
1046 /* ========================================================================== */