1 /* ========================================================================== **
4 * Copyright (C) 1991-1998 by Christopher R. Hertel
6 * Email: crh@ubiqx.mn.org
7 * -------------------------------------------------------------------------- **
9 * This module implements a simple binary tree.
11 * -------------------------------------------------------------------------- **
13 * This library is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU Library General Public
15 * License as published by the Free Software Foundation; either
16 * version 2 of the License, or (at your option) any later version.
18 * This library is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 * Library General Public License for more details.
23 * You should have received a copy of the GNU Library General Public
24 * License along with this library; if not, write to the Free
25 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 * -------------------------------------------------------------------------- **
29 * Log: ubi_BinTree.c,v
30 * Revision 4.10 2000/06/06 20:38:40 crh
31 * In the ReplaceNode() function, the old node header was being copied
32 * to the new node header using a byte-by-byte copy. This was causing
33 * the 'insure' software testing program to report a memory leak. The
34 * fix was to do a simple assignement: *newnode = *oldnode;
35 * This quieted the (errant) memory leak reports and is probably a bit
36 * faster than the bytewise copy.
38 * Revision 4.9 2000/01/08 23:24:30 crh
39 * Clarified a variety of if( pointer ) lines, replacing them with
40 * if( NULL != pointer ). This is more correct, and I have heard
41 * of at least one (obscure?) system out there that uses a non-zero
43 * Also, speed improvement in Neighbor(). It was comparing pointers
44 * when it could have compared two gender values. The pointer
45 * comparison was somewhat indirect (does pointer equal the pointer
46 * of the parent of the node pointed to by pointer). Urq.
48 * Revision 4.8 1999/09/22 03:40:30 crh
49 * Modified ubi_btTraverse() and ubi_btKillTree(). They now return an
50 * unsigned long indicating the number of nodes processed. The change
51 * is subtle. An empty tree formerly returned False, and now returns
54 * Revision 4.7 1998/10/21 06:14:42 crh
55 * Fixed bugs in FirstOf() and LastOf() reported by Massimo Campostrini.
56 * See function comments.
58 * Revision 4.6 1998/07/25 17:02:10 crh
59 * Added the ubi_trNewTree() macro.
61 * Revision 4.5 1998/06/04 21:29:27 crh
62 * Upper-cased defined constants (eg UBI_BINTREE_H) in some header files.
63 * This is more "standard", and is what people expect. Weird, eh?
65 * Revision 4.4 1998/06/03 17:42:46 crh
66 * Further fiddling with sys_include.h. It's now in ubi_BinTree.h which is
67 * included by all of the binary tree files.
69 * Reminder: Some of the ubi_tr* macros in ubi_BinTree.h are redefined in
70 * ubi_AVLtree.h and ubi_SplayTree.h. This allows easy swapping
71 * of tree types by simply changing a header. Unfortunately, the
72 * macro redefinitions in ubi_AVLtree.h and ubi_SplayTree.h will
73 * conflict if used together. You must either choose a single tree
74 * type, or use the underlying function calls directly. Compare
75 * the two header files for more information.
77 * Revision 4.3 1998/06/02 01:28:43 crh
78 * Changed ubi_null.h to sys_include.h to make it more generic.
80 * Revision 4.2 1998/05/20 04:32:36 crh
81 * The C file now includes ubi_null.h. See ubi_null.h for more info.
82 * Also, the balance and gender fields of the node were declared as
83 * signed char. As I understand it, at least one SunOS or Solaris
84 * compiler doesn't like "signed char". The declarations were
85 * wrong anyway, so I changed them to simple "char".
87 * Revision 4.1 1998/03/31 06:11:57 crh
88 * Thomas Aglassinger sent E'mail pointing out errors in the
89 * dereferencing of function pointers, and a missing typecast.
92 * Revision 4.0 1998/03/10 03:19:22 crh
93 * Added the AVL field 'balance' to the ubi_btNode structure. This means
94 * that all BinTree modules now use the same basic node structure, which
95 * greatly simplifies the AVL module.
96 * Decided that this was a big enough change to justify a new major revision
97 * number. 3.0 was an error, so we're at 4.0.
99 * Revision 2.6 1998/01/24 06:27:46 crh
100 * Added ubi_trCount() macro.
102 * Revision 2.5 1997/12/23 03:56:29 crh
103 * In this version, all constants & macros defined in the header file have
104 * the ubi_tr prefix. Also cleaned up anything that gcc complained about
105 * when run with '-pedantic -fsyntax-only -Wall'.
107 * Revision 2.4 1997/07/26 04:11:10 crh
108 * + Just to be annoying I changed ubi_TRUE and ubi_FALSE to ubi_trTRUE
110 * + There is now a type ubi_trBool to go with ubi_trTRUE and ubi_trFALSE.
111 * + There used to be something called "ubi_TypeDefs.h". I got rid of it.
112 * + Added function ubi_btLeafNode().
114 * Revision 2.3 1997/06/03 05:16:17 crh
115 * Changed TRUE and FALSE to ubi_TRUE and ubi_FALSE to avoid conflicts.
116 * Also changed the interface to function InitTree(). See the comments
117 * for this function for more information.
119 * Revision 2.2 1995/10/03 22:00:07 CRH
122 * Revision 2.1 95/03/09 23:37:10 CRH
123 * Added the ModuleID static string and function. These modules are now
126 * Revision 2.0 95/02/27 22:00:17 CRH
127 * Revision 2.0 of this program includes the following changes:
129 * 1) A fix to a major typo in the RepaceNode() function.
130 * 2) The addition of the static function Border().
131 * 3) The addition of the public functions FirstOf() and LastOf(), which
132 * use Border(). These functions are used with trees that allow
134 * 4) A complete rewrite of the Locate() function. Locate() now accepts
135 * a "comparison" operator.
136 * 5) Overall enhancements to both code and comments.
138 * I decided to give this a new major rev number because the interface has
139 * changed. In particular, there are two new functions, and changes to the
142 * Revision 1.0 93/10/15 22:44:59 CRH
143 * With this revision, I have added a set of #define's that provide a single,
144 * standard API to all existing tree modules. Until now, each of the three
145 * existing modules had a different function and typedef prefix, as follows:
149 * ubi_AVLtree ubi_avl
150 * ubi_SplayTree ubi_spt
152 * To further complicate matters, only those portions of the base module
153 * (ubi_BinTree) that were superceeded in the new module had the new names.
154 * For example, if you were using ubi_SplayTree, the locate function was
155 * called "ubi_sptLocate", but the next and previous functions remained
156 * "ubi_btNext" and "ubi_btPrev".
158 * This was not too terrible if you were familiar with the modules and knew
159 * exactly which tree model you wanted to use. If you wanted to be able to
160 * change modules (for speed comparisons, etc), things could get messy very
163 * So, I have added a set of defined names that get redefined in any of the
164 * descendant modules. To use this standardized interface in your code,
165 * simply replace all occurances of "ubi_bt", "ubi_avl", and "ubi_spt" with
166 * "ubi_tr". The "ubi_tr" names will resolve to the correct function or
167 * datatype names for the module that you are using. Just remember to
168 * include the header for that module in your program file. Because these
169 * names are handled by the preprocessor, there is no added run-time
172 * Note that the original names do still exist, and can be used if you wish
173 * to write code directly to a specific module. This should probably only be
174 * done if you are planning to implement a new descendant type, such as
175 * red/black trees. CRH
177 * V0.0 - June, 1991 - Written by Christopher R. Hertel (CRH).
179 * ========================================================================== **
182 #include "ubi_BinTree.h" /* Header for this module. */
184 /* ========================================================================== **
188 static char ModuleID
[] = "ubi_BinTree\n\
190 \tDate: 2000/06/06 20:38:40 \n\
193 /* ========================================================================== **
194 * Internal (private) functions.
197 static ubi_btNodePtr
qFind( ubi_btCompFunc cmp
,
198 ubi_btItemPtr FindMe
,
199 register ubi_btNodePtr p
)
200 /* ------------------------------------------------------------------------ **
201 * This function performs a non-recursive search of a tree for a node
202 * matching a specific key. It is called "qFind()" because it is
203 * faster that TreeFind (below).
206 * cmp - a pointer to the tree's comparison function.
207 * FindMe - a pointer to the key value for which to search.
208 * p - a pointer to the starting point of the search. <p>
209 * is considered to be the root of a subtree, and only
210 * the subtree will be searched.
213 * A pointer to a node with a key that matches the key indicated by
214 * FindMe, or NULL if no such node was found.
216 * Note: In a tree that allows duplicates, the pointer returned *might
217 * not* point to the (sequentially) first occurance of the
219 * ------------------------------------------------------------------------ **
225 && ((tmp
= ubi_trAbNormal( (*cmp
)(FindMe
, p
) )) != ubi_trEQUAL
) )
231 static ubi_btNodePtr
TreeFind( ubi_btItemPtr findme
,
233 ubi_btNodePtr
*parentp
,
235 ubi_btCompFunc CmpFunc
)
236 /* ------------------------------------------------------------------------ **
237 * TreeFind() searches a tree for a given value (findme). It will return a
238 * pointer to the target node, if found, or NULL if the target node was not
241 * TreeFind() also returns, via parameters, a pointer to the parent of the
242 * target node, and a LEFT or RIGHT value indicating which child of the
243 * parent is the target node. *If the target is not found*, then these
244 * values indicate the place at which the target *should be found*. This
245 * is useful when inserting a new node into a tree or searching for nodes
246 * "near" the target node.
248 * The parameters are:
250 * findme - is a pointer to the key information to be searched for.
251 * p - points to the root of the tree to be searched.
252 * parentp - will return a pointer to a pointer to the !parent! of the
253 * target node, which can be especially usefull if the target
255 * gender - returns LEFT or RIGHT to indicate which child of *parentp
257 * CmpFunc - points to the comparison function.
259 * This function is called by ubi_btLocate() and ubi_btInsert().
260 * ------------------------------------------------------------------------ **
263 register ubi_btNodePtr tmp_p
= p
;
264 ubi_btNodePtr tmp_pp
= NULL
;
265 char tmp_gender
= ubi_trEQUAL
;
268 while( (NULL
!= tmp_p
)
269 && (ubi_trEQUAL
!= (tmp_cmp
= ubi_trAbNormal((*CmpFunc
)(findme
, tmp_p
)))) )
271 tmp_pp
= tmp_p
; /* Keep track of previous node. */
272 tmp_gender
= (char)tmp_cmp
; /* Keep track of sex of child. */
273 tmp_p
= tmp_p
->Link
[tmp_cmp
]; /* Go to child. */
275 *parentp
= tmp_pp
; /* Return results. */
276 *gender
= tmp_gender
;
280 static void ReplaceNode( ubi_btNodePtr
*parent
,
281 ubi_btNodePtr oldnode
,
282 ubi_btNodePtr newnode
)
283 /* ------------------------------------------------------------------------ **
284 * Remove node oldnode from the tree, replacing it with node newnode.
287 * parent - A pointer to he parent pointer of the node to be
288 * replaced. <parent> may point to the Link[] field of
289 * a parent node, or it may indicate the root pointer at
290 * the top of the tree.
291 * oldnode - A pointer to the node that is to be replaced.
292 * newnode - A pointer to the node that is to be installed in the
293 * place of <*oldnode>.
295 * Notes: Don't forget to free oldnode.
296 * Also, this function used to have a really nasty typo
297 * bug. "oldnode" and "newnode" were swapped in the line
299 * ((unsigned char *)newnode)[i] = ((unsigned char *)oldnode)[i];
301 * ------------------------------------------------------------------------ **
304 *newnode
= *oldnode
; /* Copy node internals to new node. */
306 (*parent
) = newnode
; /* Old node's parent points to new child. */
307 /* Now tell the children about their new step-parent. */
308 if( oldnode
->Link
[ubi_trLEFT
] )
309 (oldnode
->Link
[ubi_trLEFT
])->Link
[ubi_trPARENT
] = newnode
;
310 if( oldnode
->Link
[ubi_trRIGHT
] )
311 (oldnode
->Link
[ubi_trRIGHT
])->Link
[ubi_trPARENT
] = newnode
;
314 static void SwapNodes( ubi_btRootPtr RootPtr
,
316 ubi_btNodePtr Node2
)
317 /* ------------------------------------------------------------------------ **
318 * This function swaps two nodes in the tree. Node1 will take the place of
319 * Node2, and Node2 will fill in the space left vacant by Node 1.
322 * RootPtr - pointer to the tree header structure for this tree.
324 * > These are the two nodes which are to be swapped.
328 * This function does a three step swap, using a dummy node as a place
329 * holder. This function is used by ubi_btRemove().
330 * ------------------------------------------------------------------------ **
333 ubi_btNodePtr
*Parent
;
335 ubi_btNodePtr dummy_p
= &dummy
;
337 /* Replace Node 1 with the dummy, thus removing Node1 from the tree. */
338 if( NULL
!= Node1
->Link
[ubi_trPARENT
] )
339 Parent
= &((Node1
->Link
[ubi_trPARENT
])->Link
[(int)(Node1
->gender
)]);
341 Parent
= &(RootPtr
->root
);
342 ReplaceNode( Parent
, Node1
, dummy_p
);
344 /* Swap Node 1 with Node 2, placing Node 1 back into the tree. */
345 if( NULL
!= Node2
->Link
[ubi_trPARENT
] )
346 Parent
= &((Node2
->Link
[ubi_trPARENT
])->Link
[(int)(Node2
->gender
)]);
348 Parent
= &(RootPtr
->root
);
349 ReplaceNode( Parent
, Node2
, Node1
);
351 /* Swap Node 2 and the dummy, thus placing Node 2 back into the tree. */
352 if( NULL
!= dummy_p
->Link
[ubi_trPARENT
] )
353 Parent
= &((dummy_p
->Link
[ubi_trPARENT
])->Link
[(int)(dummy_p
->gender
)]);
355 Parent
= &(RootPtr
->root
);
356 ReplaceNode( Parent
, dummy_p
, Node2
);
359 /* -------------------------------------------------------------------------- **
360 * These routines allow you to walk through the tree, forwards or backwards.
363 static ubi_btNodePtr
SubSlide( register ubi_btNodePtr P
,
364 register int whichway
)
365 /* ------------------------------------------------------------------------ **
366 * Slide down the side of a subtree.
368 * Given a starting node, this function returns a pointer to the LEFT-, or
369 * RIGHT-most descendent, *or* (if whichway is PARENT) to the tree root.
371 * Input: P - a pointer to a starting place.
372 * whichway - the direction (LEFT, RIGHT, or PARENT) in which to
374 * Output: A pointer to a node that is either the root, or has no
375 * whichway-th child but is within the subtree of P. Note that
376 * the return value may be the same as P. The return value *will
377 * be* NULL if P is NULL.
378 * ------------------------------------------------------------------------ **
383 while( NULL
!= P
->Link
[ whichway
] )
384 P
= P
->Link
[ whichway
];
388 static ubi_btNodePtr
Neighbor( register ubi_btNodePtr P
,
389 register int whichway
)
390 /* ------------------------------------------------------------------------ **
391 * Given starting point p, return the (key order) next or preceeding node
394 * Input: P - Pointer to our starting place node.
395 * whichway - the direction in which to travel to find the
396 * neighbor, i.e., the RIGHT neighbor or the LEFT
399 * Output: A pointer to the neighboring node, or NULL if P was NULL.
401 * Notes: If whichway is PARENT, the results are unpredictable.
402 * ------------------------------------------------------------------------ **
407 if( NULL
!= P
->Link
[ whichway
] )
408 return( SubSlide( P
->Link
[ whichway
], (char)ubi_trRevWay(whichway
) ) );
410 while( NULL
!= P
->Link
[ ubi_trPARENT
] )
412 if( whichway
== P
->gender
)
413 P
= P
->Link
[ ubi_trPARENT
];
415 return( P
->Link
[ ubi_trPARENT
] );
421 static ubi_btNodePtr
Border( ubi_btRootPtr RootPtr
,
422 ubi_btItemPtr FindMe
,
425 /* ------------------------------------------------------------------------ **
426 * Given starting point p, which has a key value equal to *FindMe, locate
427 * the first (index order) node with the same key value.
429 * This function is useful in trees that have can have duplicate keys.
430 * For example, consider the following tree:
432 * 2 If <p> points to the root and <whichway> is RIGHT, 3
433 * / \ then the return value will be a pointer to the / \
434 * 2 2 RIGHT child of the root node. The tree on 2 5
435 * / / \ the right shows the order of traversal. / / \
438 * Input: RootPtr - Pointer to the tree root structure.
439 * FindMe - Key value for comparisons.
440 * p - Pointer to the starting-point node.
441 * whichway - the direction in which to travel to find the
442 * neighbor, i.e., the RIGHT neighbor or the LEFT
445 * Output: A pointer to the first (index, or "traversal", order) node with
446 * a Key value that matches *FindMe.
448 * Notes: If whichway is PARENT, or if the tree does not allow duplicate
449 * keys, this function will return <p>.
450 * ------------------------------------------------------------------------ **
453 register ubi_btNodePtr q
;
455 /* Exit if there's nothing that can be done. */
456 if( !ubi_trDups_OK( RootPtr
) || (ubi_trPARENT
== whichway
) )
459 /* First, if needed, move up the tree. We need to get to the root of the
460 * subtree that contains all of the matching nodes.
462 q
= p
->Link
[ubi_trPARENT
];
464 && (ubi_trEQUAL
== ubi_trAbNormal( (*(RootPtr
->cmp
))(FindMe
, q
) )) )
467 q
= p
->Link
[ubi_trPARENT
];
470 /* Next, move back down in the "whichway" direction. */
471 q
= p
->Link
[whichway
];
474 q
= qFind( RootPtr
->cmp
, FindMe
, q
);
478 q
= p
->Link
[whichway
];
485 /* ========================================================================== **
486 * Exported utilities.
489 long ubi_btSgn( register long x
)
490 /* ------------------------------------------------------------------------ **
491 * Return the sign of x; {negative,zero,positive} ==> {-1, 0, 1}.
493 * Input: x - a signed long integer value.
495 * Output: the "sign" of x, represented as follows:
497 * 0 == zero (no sign)
500 * Note: This utility is provided in order to facilitate the conversion
501 * of C comparison function return values into BinTree direction
502 * values: {LEFT, PARENT, EQUAL}. It is INCORPORATED into the
503 * ubi_trAbNormal() conversion macro!
505 * ------------------------------------------------------------------------ **
508 return( (x
)?((x
>0)?(1):(-1)):(0) );
511 ubi_btNodePtr
ubi_btInitNode( ubi_btNodePtr NodePtr
)
512 /* ------------------------------------------------------------------------ **
513 * Initialize a tree node.
515 * Input: a pointer to a ubi_btNode structure to be initialized.
516 * Output: a pointer to the initialized ubi_btNode structure (ie. the
517 * same as the input pointer).
518 * ------------------------------------------------------------------------ **
521 NodePtr
->Link
[ ubi_trLEFT
] = NULL
;
522 NodePtr
->Link
[ ubi_trPARENT
] = NULL
;
523 NodePtr
->Link
[ ubi_trRIGHT
] = NULL
;
524 NodePtr
->gender
= ubi_trEQUAL
;
525 NodePtr
->balance
= ubi_trEQUAL
;
527 } /* ubi_btInitNode */
529 ubi_btRootPtr
ubi_btInitTree( ubi_btRootPtr RootPtr
,
530 ubi_btCompFunc CompFunc
,
532 /* ------------------------------------------------------------------------ **
533 * Initialize the fields of a Tree Root header structure.
535 * Input: RootPtr - a pointer to an ubi_btRoot structure to be
537 * CompFunc - a pointer to a comparison function that will be used
538 * whenever nodes in the tree must be compared against
540 * Flags - One bytes worth of flags. Flags include
541 * ubi_trOVERWRITE and ubi_trDUPKEY. See the header
542 * file for more info.
544 * Output: a pointer to the initialized ubi_btRoot structure (ie. the
545 * same value as RootPtr).
547 * Note: The interface to this function has changed from that of
548 * previous versions. The <Flags> parameter replaces two
549 * boolean parameters that had the same basic effect.
551 * ------------------------------------------------------------------------ **
556 RootPtr
->root
= NULL
;
558 RootPtr
->cmp
= CompFunc
;
559 RootPtr
->flags
= (Flags
& ubi_trDUPKEY
) ? ubi_trDUPKEY
: Flags
;
560 } /* There are only two supported flags, and they are
561 * mutually exclusive. ubi_trDUPKEY takes precedence
562 * over ubi_trOVERWRITE.
565 } /* ubi_btInitTree */
567 ubi_trBool
ubi_btInsert( ubi_btRootPtr RootPtr
,
568 ubi_btNodePtr NewNode
,
569 ubi_btItemPtr ItemPtr
,
570 ubi_btNodePtr
*OldNode
)
571 /* ------------------------------------------------------------------------ **
572 * This function uses a non-recursive algorithm to add a new element to the
575 * Input: RootPtr - a pointer to the ubi_btRoot structure that indicates
576 * the root of the tree to which NewNode is to be added.
577 * NewNode - a pointer to an ubi_btNode structure that is NOT
579 * ItemPtr - A pointer to the sort key that is stored within
580 * *NewNode. ItemPtr MUST point to information stored
581 * in *NewNode or an EXACT DUPLICATE. The key data
582 * indicated by ItemPtr is used to place the new node
584 * OldNode - a pointer to an ubi_btNodePtr. When searching
585 * the tree, a duplicate node may be found. If
586 * duplicates are allowed, then the new node will
587 * be simply placed into the tree. If duplicates
588 * are not allowed, however, then one of two things
590 * 1) if overwritting *is not* allowed, this
591 * function will return FALSE (indicating that
592 * the new node could not be inserted), and
593 * *OldNode will point to the duplicate that is
595 * 2) if overwritting *is* allowed, then this
596 * function will swap **OldNode for *NewNode.
597 * In this case, *OldNode will point to the node
598 * that was removed (thus allowing you to free
600 * ** If you are using overwrite mode, ALWAYS **
601 * ** check the return value of this parameter! **
602 * Note: You may pass NULL in this parameter, the
603 * function knows how to cope. If you do this,
604 * however, there will be no way to return a
605 * pointer to an old (ie. replaced) node (which is
606 * a problem if you are using overwrite mode).
608 * Output: a boolean value indicating success or failure. The function
609 * will return FALSE if the node could not be added to the tree.
610 * Such failure will only occur if duplicates are not allowed,
611 * nodes cannot be overwritten, AND a duplicate key was found
613 * ------------------------------------------------------------------------ **
616 ubi_btNodePtr OtherP
,
620 if( NULL
== OldNode
) /* If they didn't give us a pointer, supply our own. */
623 (void)ubi_btInitNode( NewNode
); /* Init the new node's BinTree fields. */
625 /* Find a place for the new node. */
626 *OldNode
= TreeFind(ItemPtr
, (RootPtr
->root
), &parent
, &tmp
, (RootPtr
->cmp
));
628 /* Now add the node to the tree... */
629 if( NULL
== (*OldNode
) ) /* The easy one: we have a space for a new node! */
632 RootPtr
->root
= NewNode
;
635 parent
->Link
[(int)tmp
] = NewNode
;
636 NewNode
->Link
[ubi_trPARENT
] = parent
;
637 NewNode
->gender
= tmp
;
640 return( ubi_trTRUE
);
643 /* If we reach this point, we know that a duplicate node exists. This
644 * section adds the node to the tree if duplicate keys are allowed.
646 if( ubi_trDups_OK(RootPtr
) ) /* Key exists, add duplicate */
656 if( tmp
== ubi_trEQUAL
)
658 q
= q
->Link
[(int)tmp
];
660 tmp
= ubi_trAbNormal( (*(RootPtr
->cmp
))(ItemPtr
, q
) );
662 parent
->Link
[(int)tmp
] = NewNode
;
663 NewNode
->Link
[ubi_trPARENT
] = parent
;
664 NewNode
->gender
= tmp
;
666 return( ubi_trTRUE
);
669 /* If we get to *this* point, we know that we are not allowed to have
670 * duplicate nodes, but our node keys match, so... may we replace the
673 if( ubi_trOvwt_OK(RootPtr
) ) /* Key exists, we replace */
676 ReplaceNode( &(RootPtr
->root
), *OldNode
, NewNode
);
678 ReplaceNode( &(parent
->Link
[(int)((*OldNode
)->gender
)]),
680 return( ubi_trTRUE
);
683 return( ubi_trFALSE
); /* Failure: could not replace an existing node. */
686 ubi_btNodePtr
ubi_btRemove( ubi_btRootPtr RootPtr
,
687 ubi_btNodePtr DeadNode
)
688 /* ------------------------------------------------------------------------ **
689 * This function removes the indicated node from the tree.
691 * Input: RootPtr - A pointer to the header of the tree that contains
692 * the node to be removed.
693 * DeadNode - A pointer to the node that will be removed.
695 * Output: This function returns a pointer to the node that was removed
696 * from the tree (ie. the same as DeadNode).
698 * Note: The node MUST be in the tree indicated by RootPtr. If not,
699 * strange and evil things will happen to your trees.
700 * ------------------------------------------------------------------------ **
707 /* if the node has both left and right subtrees, then we have to swap
708 * it with another node. The other node we choose will be the Prev()ious
709 * node, which is garunteed to have no RIGHT child.
711 if( (NULL
!= DeadNode
->Link
[ubi_trLEFT
])
712 && (NULL
!= DeadNode
->Link
[ubi_trRIGHT
]) )
713 SwapNodes( RootPtr
, DeadNode
, ubi_btPrev( DeadNode
) );
715 /* The parent of the node to be deleted may be another node, or it may be
716 * the root of the tree. Since we're not sure, it's best just to have
717 * a pointer to the parent pointer, whatever it is.
719 if( NULL
== DeadNode
->Link
[ubi_trPARENT
] )
720 parentp
= &( RootPtr
->root
);
722 parentp
= &((DeadNode
->Link
[ubi_trPARENT
])->Link
[(int)(DeadNode
->gender
)]);
724 /* Now link the parent to the only grand-child and patch up the gender. */
725 tmp
= ((DeadNode
->Link
[ubi_trLEFT
])?ubi_trLEFT
:ubi_trRIGHT
);
727 p
= (DeadNode
->Link
[tmp
]);
730 p
->Link
[ubi_trPARENT
] = DeadNode
->Link
[ubi_trPARENT
];
731 p
->gender
= DeadNode
->gender
;
735 /* Finished, reduce the node count and return. */
740 ubi_btNodePtr
ubi_btLocate( ubi_btRootPtr RootPtr
,
741 ubi_btItemPtr FindMe
,
742 ubi_trCompOps CompOp
)
743 /* ------------------------------------------------------------------------ **
744 * The purpose of ubi_btLocate() is to find a node or set of nodes given
745 * a target value and a "comparison operator". The Locate() function is
746 * more flexible and (in the case of trees that may contain dupicate keys)
747 * more precise than the ubi_btFind() function. The latter is faster,
748 * but it only searches for exact matches and, if the tree contains
749 * duplicates, Find() may return a pointer to any one of the duplicate-
753 * RootPtr - A pointer to the header of the tree to be searched.
754 * FindMe - An ubi_btItemPtr that indicates the key for which to
756 * CompOp - One of the following:
757 * CompOp Return a pointer to the node with
758 * ------ ---------------------------------
759 * ubi_trLT - the last key value that is less
761 * ubi_trLE - the first key matching FindMe, or
762 * the last key that is less than
764 * ubi_trEQ - the first key matching FindMe.
765 * ubi_trGE - the first key matching FindMe, or the
766 * first key greater than FindMe.
767 * ubi_trGT - the first key greater than FindMe.
769 * A pointer to the node matching the criteria listed above under
770 * CompOp, or NULL if no node matched the criteria.
773 * In the case of trees with duplicate keys, Locate() will behave as
777 * Keys: 1 2 2 2 3 3 3 3 3 4 4 Keys: 1 1 2 2 2 4 4 5 5 5 6
781 * That is, when returning a pointer to a node with a key that is LESS
782 * THAN the target key (FindMe), Locate() will return a pointer to the
783 * LAST matching node.
784 * When returning a pointer to a node with a key that is GREATER
785 * THAN the target key (FindMe), Locate() will return a pointer to the
786 * FIRST matching node.
788 * See Also: ubi_btFind(), ubi_btFirstOf(), ubi_btLastOf().
789 * ------------------------------------------------------------------------ **
792 register ubi_btNodePtr p
;
793 ubi_btNodePtr parent
;
796 /* Start by searching for a matching node. */
797 p
= TreeFind( FindMe
,
803 if( NULL
!= p
) /* If we have found a match, we can resolve as follows: */
807 case ubi_trLT
: /* It's just a jump to the left... */
808 p
= Border( RootPtr
, FindMe
, p
, ubi_trLEFT
);
809 return( Neighbor( p
, ubi_trLEFT
) );
810 case ubi_trGT
: /* ...and then a jump to the right. */
811 p
= Border( RootPtr
, FindMe
, p
, ubi_trRIGHT
);
812 return( Neighbor( p
, ubi_trRIGHT
) );
814 p
= Border( RootPtr
, FindMe
, p
, ubi_trLEFT
);
819 /* Else, no match. */
820 if( ubi_trEQ
== CompOp
) /* If we were looking for an exact match... */
821 return( NULL
); /* ...forget it. */
823 /* We can still return a valid result for GT, GE, LE, and LT.
824 * <parent> points to a node with a value that is either just before or
825 * just after the target value.
826 * Remaining possibilities are LT and GT (including LE & GE).
828 if( (ubi_trLT
== CompOp
) || (ubi_trLE
== CompOp
) )
829 return( (ubi_trLEFT
== whichkid
) ? Neighbor( parent
, whichkid
) : parent
);
831 return( (ubi_trRIGHT
== whichkid
) ? Neighbor( parent
, whichkid
) : parent
);
834 ubi_btNodePtr
ubi_btFind( ubi_btRootPtr RootPtr
,
835 ubi_btItemPtr FindMe
)
836 /* ------------------------------------------------------------------------ **
837 * This function performs a non-recursive search of a tree for any node
838 * matching a specific key.
841 * RootPtr - a pointer to the header of the tree to be searched.
842 * FindMe - a pointer to the key value for which to search.
845 * A pointer to a node with a key that matches the key indicated by
846 * FindMe, or NULL if no such node was found.
848 * Note: In a tree that allows duplicates, the pointer returned *might
849 * not* point to the (sequentially) first occurance of the
850 * desired key. In such a tree, it may be more useful to use
852 * ------------------------------------------------------------------------ **
855 return( qFind( RootPtr
->cmp
, FindMe
, RootPtr
->root
) );
858 ubi_btNodePtr
ubi_btNext( ubi_btNodePtr P
)
859 /* ------------------------------------------------------------------------ **
860 * Given the node indicated by P, find the (sorted order) Next node in the
862 * Input: P - a pointer to a node that exists in a binary tree.
863 * Output: A pointer to the "next" node in the tree, or NULL if P pointed
864 * to the "last" node in the tree or was NULL.
865 * ------------------------------------------------------------------------ **
868 return( Neighbor( P
, ubi_trRIGHT
) );
871 ubi_btNodePtr
ubi_btPrev( ubi_btNodePtr P
)
872 /* ------------------------------------------------------------------------ **
873 * Given the node indicated by P, find the (sorted order) Previous node in
875 * Input: P - a pointer to a node that exists in a binary tree.
876 * Output: A pointer to the "previous" node in the tree, or NULL if P
877 * pointed to the "first" node in the tree or was NULL.
878 * ------------------------------------------------------------------------ **
881 return( Neighbor( P
, ubi_trLEFT
) );
884 ubi_btNodePtr
ubi_btFirst( ubi_btNodePtr P
)
885 /* ------------------------------------------------------------------------ **
886 * Given the node indicated by P, find the (sorted order) First node in the
887 * subtree of which *P is the root.
888 * Input: P - a pointer to a node that exists in a binary tree.
889 * Output: A pointer to the "first" node in a subtree that has *P as its
890 * root. This function will return NULL only if P is NULL.
891 * Note: In general, you will be passing in the value of the root field
892 * of an ubi_btRoot structure.
893 * ------------------------------------------------------------------------ **
896 return( SubSlide( P
, ubi_trLEFT
) );
899 ubi_btNodePtr
ubi_btLast( ubi_btNodePtr P
)
900 /* ------------------------------------------------------------------------ **
901 * Given the node indicated by P, find the (sorted order) Last node in the
902 * subtree of which *P is the root.
903 * Input: P - a pointer to a node that exists in a binary tree.
904 * Output: A pointer to the "last" node in a subtree that has *P as its
905 * root. This function will return NULL only if P is NULL.
906 * Note: In general, you will be passing in the value of the root field
907 * of an ubi_btRoot structure.
908 * ------------------------------------------------------------------------ **
911 return( SubSlide( P
, ubi_trRIGHT
) );
914 ubi_btNodePtr
ubi_btFirstOf( ubi_btRootPtr RootPtr
,
915 ubi_btItemPtr MatchMe
,
917 /* ------------------------------------------------------------------------ **
918 * Given a tree that a allows duplicate keys, and a pointer to a node in
919 * the tree, this function will return a pointer to the first (traversal
920 * order) node with the same key value.
922 * Input: RootPtr - A pointer to the root of the tree.
923 * MatchMe - A pointer to the key value. This should probably
924 * point to the key within node *p.
925 * p - A pointer to a node in the tree.
926 * Output: A pointer to the first node in the set of nodes with keys
928 * Notes: Node *p MUST be in the set of nodes with keys matching
929 * <FindMe>. If not, this function will return NULL.
931 * 4.7: Bug found & fixed by Massimo Campostrini,
932 * Istituto Nazionale di Fisica Nucleare, Sezione di Pisa.
934 * ------------------------------------------------------------------------ **
937 /* If our starting point is invalid, return NULL. */
939 || (ubi_trEQUAL
!= ubi_trAbNormal( (*(RootPtr
->cmp
))( MatchMe
, p
) )) )
941 return( Border( RootPtr
, MatchMe
, p
, ubi_trLEFT
) );
942 } /* ubi_btFirstOf */
944 ubi_btNodePtr
ubi_btLastOf( ubi_btRootPtr RootPtr
,
945 ubi_btItemPtr MatchMe
,
947 /* ------------------------------------------------------------------------ **
948 * Given a tree that a allows duplicate keys, and a pointer to a node in
949 * the tree, this function will return a pointer to the last (traversal
950 * order) node with the same key value.
952 * Input: RootPtr - A pointer to the root of the tree.
953 * MatchMe - A pointer to the key value. This should probably
954 * point to the key within node *p.
955 * p - A pointer to a node in the tree.
956 * Output: A pointer to the last node in the set of nodes with keys
958 * Notes: Node *p MUST be in the set of nodes with keys matching
959 * <FindMe>. If not, this function will return NULL.
961 * 4.7: Bug found & fixed by Massimo Campostrini,
962 * Istituto Nazionale di Fisica Nucleare, Sezione di Pisa.
964 * ------------------------------------------------------------------------ **
967 /* If our starting point is invalid, return NULL. */
969 || (ubi_trEQUAL
!= ubi_trAbNormal( (*(RootPtr
->cmp
))( MatchMe
, p
) )) )
971 return( Border( RootPtr
, MatchMe
, p
, ubi_trRIGHT
) );
974 unsigned long ubi_btTraverse( ubi_btRootPtr RootPtr
,
975 ubi_btActionRtn EachNode
,
977 /* ------------------------------------------------------------------------ **
978 * Traverse a tree in sorted order (non-recursively). At each node, call
979 * (*EachNode)(), passing a pointer to the current node, and UserData as the
982 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
983 * the tree to be traversed.
984 * EachNode - a pointer to a function to be called at each node
985 * as the node is visited.
986 * UserData - a generic pointer that may point to anything that
989 * Output: A count of the number of nodes visited. This will be zero
990 * if the tree is empty.
992 * ------------------------------------------------------------------------ **
995 ubi_btNodePtr p
= ubi_btFirst( RootPtr
->root
);
996 unsigned long count
= 0;
1000 (*EachNode
)( p
, UserData
);
1002 p
= ubi_btNext( p
);
1005 } /* ubi_btTraverse */
1007 unsigned long ubi_btKillTree( ubi_btRootPtr RootPtr
,
1008 ubi_btKillNodeRtn FreeNode
)
1009 /* ------------------------------------------------------------------------ **
1010 * Delete an entire tree (non-recursively) and reinitialize the ubi_btRoot
1011 * structure. Return a count of the number of nodes deleted.
1013 * Input: RootPtr - a pointer to an ubi_btRoot structure that indicates
1014 * the root of the tree to delete.
1015 * FreeNode - a function that will be called for each node in the
1016 * tree to deallocate the memory used by the node.
1018 * Output: The number of nodes removed from the tree.
1019 * A value of 0 will be returned if:
1020 * - The tree actually contains 0 entries.
1021 * - the value of <RootPtr> is NULL, in which case the tree is
1022 * assumed to be empty
1023 * - the value of <FreeNode> is NULL, in which case entries
1024 * cannot be removed, so 0 is returned. *Make sure that you
1025 * provide a valid value for <FreeNode>*.
1026 * In all other cases, you should get a positive value equal to
1027 * the value of RootPtr->count upon entry.
1029 * ------------------------------------------------------------------------ **
1033 unsigned long count
= 0;
1035 if( (NULL
== RootPtr
) || (NULL
== FreeNode
) )
1038 p
= ubi_btFirst( RootPtr
->root
);
1042 while( q
->Link
[ubi_trRIGHT
] )
1043 q
= SubSlide( q
->Link
[ubi_trRIGHT
], ubi_trLEFT
);
1044 p
= q
->Link
[ubi_trPARENT
];
1046 p
->Link
[ ((p
->Link
[ubi_trLEFT
] == q
)?ubi_trLEFT
:ubi_trRIGHT
) ] = NULL
;
1047 (*FreeNode
)((void *)q
);
1052 (void)ubi_btInitTree( RootPtr
,
1056 } /* ubi_btKillTree */
1058 ubi_btNodePtr
ubi_btLeafNode( ubi_btNodePtr leader
)
1059 /* ------------------------------------------------------------------------ **
1060 * Returns a pointer to a leaf node.
1062 * Input: leader - Pointer to a node at which to start the descent.
1064 * Output: A pointer to a leaf node selected in a somewhat arbitrary
1067 * Notes: I wrote this function because I was using splay trees as a
1068 * database cache. The cache had a maximum size on it, and I
1069 * needed a way of choosing a node to sacrifice if the cache
1070 * became full. In a splay tree, less recently accessed nodes
1071 * tend toward the bottom of the tree, meaning that leaf nodes
1072 * are good candidates for removal. (I really can't think of
1073 * any other reason to use this function.)
1074 * + In a simple binary tree or an AVL tree, the most recently
1075 * added nodes tend to be nearer the bottom, making this a *bad*
1076 * way to choose which node to remove from the cache.
1077 * + Randomizing the traversal order is probably a good idea. You
1078 * can improve the randomization of leaf node selection by passing
1079 * in pointers to nodes other than the root node each time. A
1080 * pointer to any node in the tree will do. Of course, if you
1081 * pass a pointer to a leaf node you'll get the same thing back.
1083 * ------------------------------------------------------------------------ **
1086 ubi_btNodePtr follower
= NULL
;
1087 int whichway
= ubi_trLEFT
;
1089 while( NULL
!= leader
)
1092 leader
= follower
->Link
[ whichway
];
1093 if( NULL
== leader
)
1095 whichway
= ubi_trRevWay( whichway
);
1096 leader
= follower
->Link
[ whichway
];
1101 } /* ubi_btLeafNode */
1103 int ubi_btModuleID( int size
, char *list
[] )
1104 /* ------------------------------------------------------------------------ **
1105 * Returns a set of strings that identify the module.
1107 * Input: size - The number of elements in the array <list>.
1108 * list - An array of pointers of type (char *). This array
1109 * should, initially, be empty. This function will fill
1110 * in the array with pointers to strings.
1111 * Output: The number of elements of <list> that were used. If this value
1112 * is less than <size>, the values of the remaining elements are
1115 * Notes: Please keep in mind that the pointers returned indicate strings
1116 * stored in static memory. Don't free() them, don't write over
1117 * them, etc. Just read them.
1118 * ------------------------------------------------------------------------ **
1129 } /* ubi_btModuleID */
1132 /* ========================================================================== */