IceWalkers.com - Linux Software downloads and news
Name : Password :
Linux SoftwareLinux RPMLinux HowtosLink UsAboutAdvertise

tsearch (3)

TSEARCH(3)                 Linux Programmer's Manual                TSEARCH(3)



NAME
       tsearch, tfind, tdelete, twalk - manage a binary tree

SYNOPSIS
       #include<search.h>

       void*tsearch(constvoid*key,void**rootp,
                       int(*compar)(constvoid*,constvoid*));

       void*tfind(constvoid*key,constvoid**rootp,
                       int(*compar)(constvoid*,constvoid*));

       void*tdelete(constvoid*key,void**rootp,
                       int(*compar)(constvoid*,constvoid*));

       voidtwalk(constvoid*root,void(*action)(constvoid*nodep,
                                          constVISIT which,
                                          constint depth));

       #define_GNU_SOURCE
       #include<search.h>

       voidtdestroy(void*root,void(*free_node)(void*nodep));

DESCRIPTION
       tsearch, tfind, twalk, and tdelete manage a binary tree.  They are gen-
       eralized from Knuth (6.2.2) Algorithm T.  The first field in each  node
       of  the tree is a pointer to the corresponding data item.  (The calling
       program must store the actual data.)  compar  points  to  a  comparison
       routine,  which takes pointers to two items.  It should return an inte-
       ger which is negative, zero, or  positive,  depending  on  whether  the
       first item is less than, equal to, or greater than the second.

       tsearch  searches  the  tree for an item.  key points to the item to be
       searched for.  rootp points to a variable which points to the  root  of
       the tree.  If the tree is empty, then the variable that rootp points to
       should be set to NULL.  If the item is found in the tree, then  tsearch
       returns a pointer to it.  If it is not found, then tsearch adds it, and
       returns a pointer to the newly added item.

       tfind is like tsearch, except that if the item is not found, then tfind
       returns NULL.

       tdelete  deletes  an item from the tree.  Its arguments are the same as
       for tsearch.

       twalk performs depth-first, left-to-right traversal of a  binary  tree.
       root  points  to  the starting node for the traversal.  If that node is
       not the root, then only part of the tree will be visited.  twalk  calls
       the  user  function  action each time a node is visited (that is, three
       times for an internal node, and once for a  leaf).   action,  in  turn,
       takes  three  arguments.  The first is a pointer to the node being vis-
       ited.  The second is an integer which takes  on  the  values  preorder,
       postorder, and endorder depending on whether this is the first, second,
       or third visit to the internal node, or leaf if it is the single  visit
       to  a leaf node.  (These symbols are defined in <search.h>.)  The third
       argument is the depth of the node, with zero being the root.

       (More commonly, preorder, postorder, and endorder  are  known  as  pre-
       order,  inorder, and postorder: before visiting the children, after the
       first and before the second, and after visiting the children. Thus, the
       choice of name postorder is rather confusing.)

       tdestroy  removes  the  whole  tree  pointed  to  by rootp, freeing all
       resources allocated by the tsearch function. For the data in each  tree
       node  the  function  free_node  is  called.  The pointer to the data is
       passed as the argument to the function. If no such  work  is  necessary
       free_node must point to a function doing nothing.

RETURNVALUE
       tsearch  returns  a  pointer  to a matching item in the tree, or to the
       newly added item, or NULL if there was insufficient memory to  add  the
       item.   tfind  returns  a  pointer  to the item, or NULL if no match is
       found.  If there are multiple elements that match the key, the  element
       returned is unspecified.

       tdelete returns a pointer to the parent of the item deleted, or NULL if
       the item was not found.

       tsearch, tfind, and tdelete also return  NULL  if  rootp  was  NULL  on
       entry.

WARNINGS
       twalk  takes  a  pointer  to the root, while the other functions take a
       pointer to a variable which points to the root.

       twalk uses postorder to mean "after the left subtree,  but  before  the
       right  subtree".   Some  authorities  would  call  this  "inorder", and
       reserve "postorder" to mean "after both subtrees".

       tdelete frees the memory required for the node in the tree.   The  user
       is responsible for freeing the memory for the corresponding data.

       The  example  program  depends  on the fact that twalk makes no further
       reference to a node after  calling  the  user  function  with  argument
       "endorder"  or "leaf".  This works with the GNU library implementation,
       but is not in the SysV documentation.

EXAMPLE
       The following program inserts twelve random numbers into a binary tree,
       where  duplicate  numbers  are  collapsed,  then  prints the numbers in
       order.

           #include <search.h>
           #include <stdlib.h>
           #include <stdio.h>
           #include <time.h>

           void *root=NULL;

           void *xmalloc(unsigned n) {
             void *p;
             p = malloc(n);
             if(p) return p;
             fprintf(stderr, "insufficient memory\n");
             exit(1);
           }

           int compare(const void *pa, const void *pb) {
             if(*(int *)pa < *(int *)pb) return -1;
             if(*(int *)pa > *(int *)pb) return 1;
             return 0;
           }

           void action(const void *nodep, const VISIT which, const int depth) {
             int *datap;

             switch(which) {
               case preorder:
                 break;
               case postorder:
                 datap = *(int **)nodep;
                 printf("%6d\n", *datap);
                 break;
               case endorder:
                 break;
               case leaf:
                 datap = *(int **)nodep;
                 printf("%6d\n", *datap);
                 break;
             }
           }

           int main() {
             int i, *ptr;
             void *val;

             srand(time(NULL));
             for (i = 0; i < 12; i++) {
                 ptr = (int *)xmalloc(sizeof(int));
                 *ptr = rand()&0xff;
                 val = tsearch((void *)ptr, &root, compare);
                 if(val == NULL) exit(1);
             }
             twalk(root, action);
             return 0;
           }

CONFORMINGTO
       SVID.  The function tdestroy() is a GNU extension.

SEEALSO
       qsort(3), bsearch(3), hsearch(3), lsearch(3)




GNU                               1995-09-24                        TSEARCH(3)

CMSG_ALIGNfmodllroundfstrncmp
CMSG_FIRSTHDRfnmatchllroundlstrncpy
CMSG_NXTHDRfopenlocaleconvstrndup
CMSG_SPACEforkptylocaltimestrndupa
MB_CUR_MAXfpathconflockfstrnlen
MB_LEN_MAXfprintflogstrpbrk
__fbufsizefpurgelog10strptime
__flbffputclog1pstrrchr
__fpendingfputc_unlockedlogin_ttystrsep
__fpurgefputslogwtmpstrsignal
__freadablefputs_unlockedlongjmpstrspn
__freadingfputwclrand48strstr
__fsetlockingfputwc_unlockedlrintstrtod
__fwritablefputwslrintfstrtof
__fwritingfputws_unlockedlrintlstrtok
__malloc_hookfreadlroundstrtok_r
__setfpucwfread_unlockedlroundfstrtol
_flushlbffreelroundlstrtold
a64lfreeaddrinfolsearchstrtoll
abortfreehostentmakecontextstrtoq
absfreopenmallocstrtoul
acosfrexpmalloc_hookstrtoull
acoshfscanfmblenstrtouq
addmntentfseekmbrlenstrverscmp
allocafseekombrtowcstrxfrm
alphasortfsetposmbsinitsvc_destroy
argz_addftellmbsnrtowcssvc_freeargs
argz_add_sepftellombsrtowcssvc_getargs
argz_appendftimembstowcssvc_getcaller
argz_countftokmbtowcsvc_getreq
argz_createftrylockfilememalignsvc_getreqset
argz_create_sepftsmemccpysvc_register
argz_deletefts_childrenmemchrsvc_run
argz_extractfts_closememcmpsvc_sendreply
argz_insertfts_openmemcpysvc_unregister
argz_nextfts_readmemfrobsvcerr_auth
argz_replacefts_setmemmemsvcerr_decode
argz_stringifyftwmemmovesvcerr_noproc
asctimefunlockfilememrchrsvcerr_noprog
asinfwidememsetsvcerr_progvers
asinhfwprintfmkdtempsvcerr_systemerr
asprintffwritemkfifosvcerr_weakauth
assertfwrite_unlockedmkstempsvcfd_create
assert_perrorgai_strerrormktempsvcraw_create
atangammamktimesvctcp_create
atan2gammafmodfsvcudp_bufcreate
atanhgammalmpoolsvcudp_create
atexitgcvtmrand48swab
atofget_current_dir_namemtraceswapcontext
atoiget_myaddressmuntraceswprintf
atolgetaddrinfonansysconf
atollgetcnanfsyslog
atoqgetc_unlockednanlsystem
auth_destroygetcharnearbyinttan
authnone_creategetchar_unlockednearbyintftanh
authunix_creategetcwdnearbyintltcdrain
authunix_create_defaultgetdatenetlinktcflow
basenamegetdate_rnextaftertcflush
bcmpgetdelimnextafterftcgetattr
bcopygetdirentriesnextafterltcgetpgrp
bindresvportgetenvnexttowardtcgetsid
bsearchgetfsentnexttowardftcsendbreak
bstringgetfsfilenexttowardltcsetattr
btowcgetfsspecnftwtcsetpgrp
btreegetgrentnl_langinfotdelete
byteordergetgrgidnrand48telldir
bzerogetgrnamntohltempnam
callocgethostbyaddrntohstermios
callrpcgethostbynameon_exittfind
catclosegethostbyname2opendirtgamma
catgetsgethostbyname2_ropenlogtgammaf
catopengethostbyname_ropenptytgammal
cbrtgetipnodebyaddrpathconftimegm
ceilgetipnodebynamepclosetimelocal
ceilfgetlineperrortmpfile
ceillgetloadavgpmap_getmapstmpnam
cfgetispeedgetloginpmap_getporttoascii
cfgetospeedgetmntentpmap_rmtcalltolower
cfmakerawgetnameinfopmap_settoupper
cfsetispeedgetnetbyaddrpmap_unsettowctrans
cfsetospeedgetnetbynamepopentowlower
clearenvgetnetentposix_memaligntowupper
clearerrgetoptpowtrunc
clearerr_unlockedgetopt_longprintftruncf
clnt_broadcastgetopt_long_onlyprofiltruncl
clnt_callgetpasspsignaltsearch
clnt_controlgetprotobynameptsnamettyname
clnt_creategetprotobynumberputcttyname_r
clnt_destroygetprotoentputc_unlockedttyslot
clnt_freeresgetptputchartwalk
clnt_geterrgetpwputchar_unlockedtzset
clnt_pcreateerrorgetpwentputenvulimit
clnt_perrnogetpwnamputpwentundocumented
clnt_perrorgetpwuidputsungetc
clnt_spcreateerrorgetrpcbynamepututlineungetwc
clnt_sperrnogetrpcbynumberpututxlineunlocked_stdio
clnt_sperrorgetrpcentputwunlockpt
clntraw_creategetrpcportputwcunsetenv
clnttcp_creategetsputwc_unlockedupdwtmp
clntudp_bufcreategetservbynameputwcharusleep
clntudp_creategetservbyportputwchar_unlockedutmpname
clockgetserventqecvtva_arg
closedirgetttyentqecvt_rva_end
closeloggetttynamqfcvtva_start
cmsggetumaskqfcvt_rvalloc
confstrgetusershellqgcvtvasprintf
copysigngetutentqsortvdprintf
copysignfgetutidqueueverr
copysignlgetutlineraiseverrx
cosgetutxentrandversionsort
coshgetutxidrandomvfprintf
cryptgetutxlinercmdvfscanf
ctermidgetwre_compvfwprintf
ctimegetwcre_execvprintf
cuseridgetwc_unlockedreaddirvscanf
daemongetwcharreallocvsnprintf
dbgetwchar_unlockedrealpathvsprintf
dbopengetwdrecnovsscanf
difftimeglobregcompvswprintf
dirfdglobfreeregerrorvsyslog
dirnamegmtimeregexvwarn
divgrantptregexecvwarnx
dlclosegsignalregfreevwprintf
dlerrorhashregisterrpcwarn
dlopenhasmntoptremovewarnx
dlsymhcreateremquewcpcpy
dn_comphcreate_rres_initwcpncpy
dn_expandhdestroyres_mkquerywcrtomb
dprintfhdestroy_rres_querywcscasecmp
drand48herrorres_querydomainwcscat
dremhsearchres_searchwcschr
dysizehsearch_rres_sendwcscmp
ecvthstrerrorresolverwcscpy
ecvt_rhtonlrewindwcscspn
encrypthtonsrewinddirwcsdup
endfsenthypotrindexwcslen
endgrenticonvrintwcsncasecmp
endhostenticonv_closerintfwcsncat
endmntenticonv_openrintlwcsncmp
endnetentimaxabsroundwcsncpy
endprotoentindexroundfwcsnlen
endpwentinetroundlwcsnrtombs
endrpcentinet_addrrpcwcspbrk
endserventinet_atonrresvportwcsrchr
endttyentinet_lnaofrtnetlinkwcsrtombs
endusershellinet_makeaddrruserokwcsspn
endutentinet_netofscandirwcsstr
endutxentinet_networkscanfwcstok
envz_addinet_ntoaseed48wcstombs
envz_entryinet_ntopseekdirwcswidth
envz_getinet_ptonsetbufwctob
envz_mergeinfnansetbufferwctomb
envz_removeinitgroupssetenvwctrans
envz_stripinitstatesetfsentwctype
erand48insquesetgrentwcwidth
erfintrosethostentwmemchr
erfciruseroksetjmpwmemcmp
errisalnumsetkeywmemcpy
errnoisalphasetlinebufwmemmove
errxisasciisetlocalewmemset
ether_atonisattysetlogmaskwprintf
ether_aton_risblanksetmntentxdr
ether_hosttoniscntrlsetnetentxdr_accepted_reply
ether_lineisdigitsetprotoentxdr_array
ether_ntoaisgraphsetpwentxdr_authunix_parms
ether_ntoa_risinfsetrpcentxdr_bool
ether_ntohostislowersetserventxdr_bytes
execisnansetstatexdr_callhdr
execlisprintsetttyentxdr_callmsg
execleispunctsetusershellxdr_char
execlpisspacesetutentxdr_destroy
execvisuppersetutxentxdr_double
execvpiswalnumsetvbufxdr_enum
exitiswalphashm_openxdr_float
expiswblanksigaddsetxdr_free
expm1iswcntrlsigdelsetxdr_getpos
fabsiswctypesigemptysetxdr_inline
fabsfiswdigitsigfillsetxdr_int
fabsliswgraphsiginterruptxdr_long
fcloseiswlowersigismemberxdr_opaque
fclosealliswprintsiglongjmpxdr_opaque_auth
fcvtiswpunctsignbitxdr_pmap
fcvt_riswspacesigsetjmpxdr_pmaplist
fdopeniswuppersigsetopsxdr_pointer
feclearexceptiswxdigitsinxdr_reference
fegetenvisxdigitsinhxdr_rejected_reply
fegetexceptflagj0sleepxdr_replymsg
fegetroundj0fsnprintfxdr_setpos
feholdexceptj0lsprintfxdr_short
fenvj1sqrtxdr_string
feofj1fsrandxdr_u_char
feof_unlockedj1lsrand48xdr_u_int
feraiseexceptjnsrandomxdr_u_long
ferrorjnfsscanfxdr_u_short
ferror_unlockedjnlssignalxdr_union
fesetenvjrand48stdargxdr_vector
fesetexceptflagkey_decryptsessionstderrxdr_void
fesetroundkey_encryptsessionstdinxdr_wrapstring
fetestexceptkey_gendesstdioxdrmem_create
feupdateenvkey_secretkey_is_setstdio_extxdrrec_create
fflushkey_setsecretstdoutxdrrec_endofrecord
fflush_unlockedkillpgstpcpyxdrrec_eof
ffsklogctlstpncpyxdrrec_skiprecord
fgetcl64astrcasecmpxdrstdio_create
fgetc_unlockedlabsstrcatxprt_register
fgetgrentlcong48strchrxprt_unregister
fgetposldexpstrcmpy0
fgetpwentldivstrcolly0f
fgetslfindstrcpyy0l
fgets_unlockedlgammastrcspny1
fgetwclgamma_rstrdupy1f
fgetwc_unlockedlgammafstrdupay1l
fgetwslgammaf_rstrerroryn
fgetws_unlockedlgammalstrerror_rynf
filenolgammal_rstrfmonynl
fileno_unlockedllabsstrfry 
finitelldivstrftime 
flockfilellrintstring 
floorllrintfstrlen 
floorfllrintlstrncasecmp 


Inkscape 0.47
Vector graphic editor for SVG
DeleGate 9.9.6-pre5
Proxy server which runs on multiple platforms
Nano 2.1.99pre2
Emulate Pico while also offering a few enhancements.
My Money 2.0.49
Personal financial software
Linux Kernel 2.6 2.6.32-rc8
Linux Kernel
GCstar 1.5.0
Personal collections manager
ImageMagick 6.5.7.9
ImageMagick image processing studio
BibleTime 2.4
Bible study software for Linux / KDE
Tellico 2.1.1
Collection manager for books, music, videos, and bibliographies
Totem 2.28.4
Movie player for Gnome
Free IT Magazines, White Papers, eBooks, and more !
Oracle Magazine

Contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more.

Vulnerability Management for Dummies

Get all the Facts and See How to Implement a Successful Vulnerability Management Program.

Website Magazine

Has tapped premier talent in the Internet industry for our content and each and every issue will contain practical advice and insights for website owners.

Linux Software Map
Find Linux RPM
Best Rated Linux Software
Most Rated Linux Software
Linux Distributions
Linux Howtos
Quick Survey

Please take our survey and help us improve our website to serve you better.

Thank you.
Linux Software
Linux / IT Resources
Site Resources
Google
Privacy Policy
Contact Us
Submit Software
Advertising info