Beruflich Dokumente
Kultur Dokumente
BinarySearchtreeisabinarytreeinwhicheachinternalnodexstoresanelementsuch
thattheelementstoredintheleftsubtreeofxarelessthanorequaltoxandelementsstored intherightsubtreeofxaregreaterthanorequaltox.Thisiscalledbinarysearchtree property. Thebasicoperationsonabinarysearchtreetaketimeproportionaltotheheightofthetree. Foracompletebinarytreewithnoden,suchoperationsrunsin (lgn)worstcasetime.If thetreeisalinearchainofnnodes,however,thesameoperationstakes time.
(n)worstcase
TheheightoftheBinarySearchTreeequalsthenumberoflinksfromtherootnode tothedeepestnode.
ImplementationofBinarySearchTree
BinarySearchTreecanbeimplementedasalinkeddatastructureinwhicheachnodeisan objectwiththreepointerfields.Thethreepointerfieldsleft,rightandppointtothenodes
InorderTreeWalk
Duringthistypeofwalk,wevisittherootofasubtreebetweentheleftsubtreevisitand rightsubtreevisit.
PreorderTreeWalk
Inwhichwevisittherootnodebeforethenodesineithersubtree.
PostorderTreeWalk
Inwhichwevisittherootnodeafterthenodesinitssubtrees.
BinarySearchTreepropertyVsHeapProperty
Inaheap,anodeskeyisgreaterthanequaltobothofitschildren'skeys.Inbinarysearch tree,anode'skeyisgreaterthanorequaltoitschild'skeybutlessthanorequaltoright child'skey.Furthermore,thisappliestoentiresubtreeinthebinarysearchtreecase.Itis veryimportanttonotethattheheappropertydoesnothelpprintthenodesinsortedorder becausethispropertydoesnottellusinwhichsubtreethenextitemis.Iftheheapproperty couldusedtoprintthekeys(aswehaveshownabove)insortedorderinO(n)time,this wouldcontradictourknownlowerboundoncomparisonsorting. Thelaststatementimpliesthatsincesortingnelementstakes(nlgn)timeintheworst caseinthecomparisonmodel,anycomparisonbasedalgorithmforconstructingaBinary SearchTreefromarbitrarylistnelementstakes(nlgn)timeintheworstcase. Wecanshowthevalidityofthisargument(incaseyouarethinkingofbeating(nlgn) bound)asfollows:letc(n)betheworstcaserunningtimeforconstructingabinarytreeof asetofnelements.GivenannnodeBST,theinorderwalkinthetreeoutputsthekeysin sortedorder(shownabove).Sincetheworstcaserunningtimeofanycomputationbased sortingalgorithmis(nlgn),wehave c(n)+O(n)=(nlgn)
Therefore,c(n)=(nlgn).
QueryingaBinarySearchTree
ThemostcommonoperationsperformedonaBSTissearchingforakeystoredinthetree. OtheroperationsareMINIMUM,MAXIMUM,SUCCESSORandPREDESESSOR.These operationsruninO(h)timewherehistheheightofthetreei.e.,histhenumberoflinks rootnodetothedeepestnode. TheTREESEARCH(x,k)algorithmsearchesthetreerootatxforanodewhosekeyvalue equalsk.ItreturnsapointertothenodeifitexistsotherwiseNIL
TREESEARCH(x,k)
ITERATIVETREESEARCH(x,k)
1. whilexnotequalNIL.AND.key
TREESUCCESSOR(x) ifright[x]NIL thenreturnTREEMINIMUM (right[x]) elseyp[x] whileyNIL.AND.x= right[y]do xy yp[y] returny NotethatalgorithmTREEMINIMUM,TREMAXIMUM,TREESUCCESSOR,and
TREEPREDESSORneverlookatthekeys. AninordertreewalkofannnodeBSTcanbeimplementedin (n)timebyfindingthe minimumelementinthetreewithTREEMINIMUM(x)algorithmandthenmakingn1 callstoTREESUCCESSOR(x).
AnotherwayofImplementingInorderwalkonBinarySearch
Letusshowthatthisalgorithmrunsin (n)time.ForatreeT,letmTbethenumberof edgesthataretraversedbytheabovealgorithm.TherunningtimeofthealgorithmforTis (mT).Wemakefollowingclaim: mTiszeroifThasatmostonenodeand2erotherwise, whereeis thenumberofedgesinthetreeandristhelengthofthe pathfrom roottothenodeholdingthemaximumkey. Notethate=n1foranytreewithatleastonenode.Thisallowsustoprovetheclaim byinductionone(andtherefore,onn).
p2,andr=r2+1.Thistimexholdstheminimumkeyandtheactionofthe
enumerationalgorithmisthelasttwosteps.Therefore,thenumberofedgesthatare traversedbythealgorithmis
mT=1+(2e2r2)
=2(e2+1)(r2+1) =2er
Therefore,theclaimholdsforthiscase. Theclaimisprovensincee=n1,mT
eitherthesmallestkeyinTlargerthankey[x] orthelargestkeyintheTsmallerthankey[x].
ProofSupposethatxisaleftchildofy.Sincekey[y] key[x],onlywehaveto showthatthereisnonodezwithkey[y]>key[z]>key[x].Assume,tothecontrary,that thereissuchaz.Choosezsothatitholdsthesmallestkeyamongsuchnodes.Notefor everynodeu z,x,key[z] dey[u]ifandonlyifkey[x] key[u].Ifwesearchkey[z], thenthesearchpathisidenticaltothatofkey[x]untilthepathrearcheszorx.Sincexisa leaf(meaningithasnochildren),thesearchpathneverreachesx.Therefore,zisan ancestorofx.Sinceyistheparentofx(itisgiven,incaseyou'veforgotton!)andisnotz, zhastobeanancestorofy.So,key[y]>dey[z]>dey[x].However,weareassuming key[y]>key[z]>key[x],sothisisclearlyimpossible.Therefore,thereisnosuchz.
Thecasewhenxisarightchildofyiseasy.Hint:symmetric.
INSERTION
ToinsertanodeintoaBST
1. findaleafsttheappropriateplaceand 2. connectthenodetotheparentoftheleaf.
TREEINSERT(T,z) yNIL xroot[T] whilexNILdo yx ifkey[z]<key[x] thenxleft[x] elsexright[x] p[z]y ify=NIL thenroot[T]z elseifkey[z]<key[y] thenleft[y]z elseright[y]z
Likeotherprimitiveoperationsonsearchtrees,thisalgorithmbeginsattherootofthetree andtracesapathdownward.Clearly,itrunsinO(h)timeonatreeofheighth.
Sorting
Wecansortagivensetofnnumbersbyfirstbuildingabinarysearchtreecontainingthese numberbyusingTREEINSERT(x)procedurerepeatedlytoinsertthenumbersonebyone andthenprintingthenumbersbyaninordertreewalk.
Analysis
Bestcaserunningtime
PrintingtakesO(n)timeandninsertioncostO(lgn)each(treeisbalanced,halfthe insertionsareatdepthlg(n)1).ThisgivesthebestcaserunningtimeO(nlgn).
Deletion
RemovinganodefromaBSTisabitmorecomplex,sincewedonotwanttocreateany "holes"inthetree.Ifthenodehasonechildthenthechildissplicedtotheparentofthe node.Ifthenodehastwochildrenthenitssuccessorhasnoleftchildcopythesuccessor intothenodeanddeletethesuccessorinsteadTREEDELETE(T,z)removesthenode pointedtobyzfromthetreeT.ITreturnsapointertothenoderemovedsothatthenode canbeputonafreenodelist,etc.
TREEDELETE(T,z)
1. ifleft[z]=NIL.OR.right[z]=NIL 2. thenyz 3. elseyTREESUCCESSOR(z) 4. ifleft[y]NIL 5. thenxleft[y] 6. elsexright[y] 7. ifxNIL 8. thenp[x]p[y] 9. ifp[y]=NIL 10. thenroot[T]x 11. elseify=left[p[y]] 12. thenleft[p[y]]x
13. elseright[p[y]]x 14. ifyz 15. thenkey[z]key[y] 16. ifyhasotherfield,copythem,too 17. returny
TheprocedurerunsinO(h)timeonatreeofheighth.