版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
IntroductiontoAlgorithms刘东林
华东理工大学信息学院计算机系Lecture05StructuresBinarySearchTreesReview:DynamicSetsfocusondatastructuresratherthanstraightalgorithmsInparticular,structuresfordynamicsetsElementshaveakeyandsatellitedataDynamicsetssupportqueriessuchas:Search(S,k),Minimum(S),Maximum(S),Successor(S,x),Predecessor(S,x)Theymayalsosupportmodifyingoperationslike:Insert(S,x),Delete(S,x)Review:BinarySearchTreesBinarySearchTrees(BSTs)areanimportantdatastructurefordynamicsetsInadditiontosatellitedata,elementshave:key:anidentifyingfieldinducingatotalorderingleft:pointertoaleftchild(maybeNULL)right:pointertoarightchild(maybeNULL)p:pointertoaparentnode(NULLforroot)Review:BinarySearchTreesBSTproperty:
key[leftSubtree(x)]key[x]key[rightSubtree(x)]Example:FBHKDAInorderTreeWalkWhatdoesthefollowingcodedo?TreeWalk(x)TreeWalk(left[x]);print(x);TreeWalk(right[x]);A:printselementsinsorted(increasing)orderThisiscalledaninordertreewalkPreordertreewalk:printroot,thenleft,thenrightPostordertreewalk:printleft,thenright,thenrootInorderTreeWalkExample:Howlongwillatreewalktake?ProvethatinorderwalkprintsinmonotonicallyincreasingorderFBHKDAOperationsonBSTs:SearchGivenakeyandapointertoanode,returnsanelementwiththatkeyorNULL:TreeSearch(x,k)if(x=NULLork=key[x])returnx;if(k<key[x])returnTreeSearch(left[x],k);elsereturnTreeSearch(right[x],k);BSTSearch:ExampleSearchforDandC:FBHKDAOperationsonBSTs:SearchHere’sanotherfunctionthatdoesthesame:TreeSearch(x,k)while(x!=NULLandk!=key[x])if(k<key[x])x=left[x];elsex=right[x];returnx;Whichofthesetwofunctionsismoreefficient?OperationsofBSTs:InsertAddsanelementxtothetreesothatthebinarysearchtreepropertycontinuestoholdThebasicalgorithmLikethesearchprocedureaboveInsertxinplaceofNULLUsea“trailingpointer”tokeeptrackofwhereyoucamefrom(likeinsertingintosinglylinkedlist)BSTInsert:ExampleExample:InsertCFBHKDACBSTSearch/Insert:RunningTimeWhatistherunningtimeofTreeSearch()orTreeInsert()?A:O(h),whereh=heightoftreeWhatistheheightofabinarysearchtree?A:worstcase:h=O(n)whentreeisjustalinearstringofleftorrightchildrenWe’llkeepallanalysisintermsofhfornowLaterwe’llseehowtomaintainh=O(lgn)SortingWithBinarySearchTreesInformalcodeforsortingarrayAoflengthn:BSTSort(A)fori=1tonTreeInsert(A[i]);InorderTreeWalk(root);Arguethatthisis(nlgn)WhatwillbetherunningtimeintheWorstcase?Averagecase?(hint:remindyouofanything?)SortingWithBSTsAveragecaseanalysisIt’saformofquicksort!fori=1tonTreeInsert(A[i]);InorderTreeWalk(root);31826755712867526753182657SortingwithBSTsSamepartitionsaredoneaswithquicksort,butinadifferentorderInpreviousexampleEverythingwascomparedto3onceThenthoseitems<3werecomparedto1onceEtc.Samecomparisonsasquicksort,differentorder!Example:considerinserting5SortingwithBSTsSinceruntimeisproportionaltothenumberofcomparisons,sametimeasquicksort:O(nlgn)Whichdoyouthinkisbetter,quicksortorBSTsort?Why?SortingwithBSTsSinceruntimeisproportionaltothenumberofcomparisons,sametimeasquicksort:O(nlgn)Whichdoyouthinkisbetter,quicksortorBSTSort?Why?A:quicksortBetterconstantsSortsinplaceDoesn’tneedtobuilddatastructureMoreBSTOperationsBSTsaregoodformorethansorting.Forexample,canimplementapriorityqueueWhatoperationsmustapriorityqueuehave?InsertMinimumExtract-MinBSTOperations:MinimumHowcanweimplementaMinimum()query?Whatistherunningtime?BSTOperations:SuccessorFordeletion,wewillneedaSuccessor()operationDrawFig13.2Whatisthesuccessorofnode3?Node15?Node13?Whatarethegeneralrulesforfindingthesuccessorofnodex?(hint:twocases)BSTOperations:SuccessorTwocases:xhasarightsubtree:successorisminimumnodeinrightsubtreexhasnorightsubtree:successorisfirstancestorofxwhoseleftchildisalsoancestorofxIntuition:Aslongasyoumovetotheleftupthetree,you’revisitingsmallernodes.Predecessor:similaralgorithmBSTOperations:DeleteDeletionisabittricky3cases:xhasnochildren:Removexxhasonechild:Spliceoutxxhastwochildren:SwapxwithsuccessorPerformcase1or2todeleteitFBHKDACExample:deleteK
orHorBBSTOperations:DeleteWhywillcase2alwaysgotocase0orcase1?A:becausewhenxhas2children,itssuccessoristheminimuminitsrightsubtreeCouldweswapxwithpredecessorinsteadofsuccessor?A:yes.Woulditbeagoodidea?A:mightbegoodtoalternateTheEndUpnext:guaranteeingaO(lgn)heighttreeRed-BlackTreesRed-BlackTreesRed-blacktrees:BinarysearchtreesaugmentedwithnodecolorOperationsdesignedtoguaranteethattheheight
h=O(lgn)Wedescribedthepropertiesofred-blacktreesWeprovedthattheseguaranteeh=O(lgn)Next:describeoperationsonred-blacktreesRed-BlackPropertiesThered-blackproperties:1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblackNote:thismeansevery“real”nodehas2children3. Ifanodeisred,bothchildrenareblackNote:can’thave2consecutiveredsonapath4. Everypathfromnodetodescendentleafcontainsthesamenumberofblacknodes5. TherootisalwaysblackBlack-Heightblack-height:#blacknodesonpathtoleafWhatistheminimumblack-heightofanodewithheighth?A:aheight-hnodehasblack-heighth/2Theorem:Ared-blacktreewithninternalnodeshasheighth2lg(n+1)Provedby(whatelse?)inductionProvingHeightBoundThusattherootofthered-blacktree:n 2bh(root)-1 n 2h/2-1 lg(n+1)h/2 h2lg(n+1) Thush=O(lgn) RBTrees:Worst-CaseTimeSowe’veprovedthatared-blacktreehasO(lgn)heightCorollary:TheseoperationstakeO(lgn)time:Minimum(),Maximum()Successor(),Predecessor()Search()Insert()andDelete():WillalsotakeO(lgn)timeButwillneedspecialcaresincetheymodifytreeRed-BlackTrees:AnExampleColorthistree:7591212597Red-blackproperties:1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. TherootisalwaysblackInsert8Wheredoesitgo?Red-BlackTrees:
TheProblemWithInsertion125971. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. TherootisalwaysblackInsert8Wheredoesitgo?Whatcolor
shoulditbe?Red-BlackTrees:
TheProblemWithInsertion1259781. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. TherootisalwaysblackInsert8Wheredoesitgo?Whatcolor
shoulditbe?Red-BlackTrees:
TheProblemWithInsertion1259781. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. TherootisalwaysblackRed-BlackTrees:
TheProblemWithInsertionInsert11Wheredoesitgo?1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. Therootisalwaysblack125978Red-BlackTrees:
TheProblemWithInsertionInsert11Wheredoesitgo?Whatcolor?1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. Therootisalwaysblack12597811Red-BlackTrees:
TheProblemWithInsertionInsert11Wheredoesitgo?Whatcolor?Can’tbered!(#3)1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. Therootisalwaysblack12597811Red-BlackTrees:
TheProblemWithInsertionInsert11Wheredoesitgo?Whatcolor?Can’tbered!(#3)Can’tbeblack!(#4)1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. Therootisalwaysblack12597811Red-BlackTrees:
TheProblemWithInsertionInsert11Wheredoesitgo?Whatcolor?Solution:
recolorthetree1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. Therootisalwaysblack12597811Red-BlackTrees:
TheProblemWithInsertionInsert10Wheredoesitgo?1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. Therootisalwaysblack12597811Red-BlackTrees:
TheProblemWithInsertionInsert10Wheredoesitgo?Whatcolor?1. Everynodeiseitherredorblack2. Everyleaf(NULLpointer)isblack3. Ifanodeisred,bothchildrenareblack4. Everypathfromnodetodescendentleaf
containsthesamenumberofblacknodes5. Therootisalwaysblack1259781110Red-BlackTrees:
TheProblemWithInsertionInsert10Wheredoesitgo?Whatcolor?A:nocolor!Tree
istooimbalancedMustchangetreestructure
toallowrecoloringGoal:restructuretreein
O(lgn)time1259781110RBTrees:RotationOurbasicoperationforchangingtreestructureiscalledrotation:Doesrotationpreserveinorderkeyordering?WhatwouldthecodeforrightRotate()actuallydo?yxCABxAyBCrightRotate(y)leftRotate(x)rightRotate(y)RBTrees:RotationAnswer:Alotofpointermanipulationxkeepsitsleftchildykeepsitsrightchildx’srightchildesy’sleftchildx’sandy’sparentschangeWhatistherunningtime?yxCABxAyBCRotationExampleRotateleftabout9:12597811RotationExampleRotateleftabout9:51279118Red-BlackTrees:InsertionInsertion:thebasicideaInsertxintotree,colorxredOnlyr-bproperty3mightbeviolated(ifp[x]red)Ifso,moveviolationuptreeuntilaplaceisfoundwhereitcanbefixedTotaltimewillbeO(lgn)rbInsert(x)treeInsert(x);x->color=RED;//Moveviolationof#3uptree,maintaining#4asinvariant:while(x!=root&&x->p->color==RED)if(x->p==x->p->p->left)y=x->p->p->right;if(y->color==RED)x->p->color=BLACK;y->color=BLACK;x->p->p->color=RED;x=x->p->p;else//y->color==BLACKif(x==x->p->right)x=x->p;leftRotate(x);x->p->color=BLACK;x->p->p->color=RED;rightRotate(x->p->p);else//x->p==x->p->p->right(sameasabove,butwith“right”&“left”exchanged)Case1Case2Case3rbInsert(x)treeInsert(x);x->color=RED;//Moveviolationof#3uptree,maintaining#4asinvariant:while(x!=root&&x->p->color==RED)if(x->p==x->p->p->left)y=x->p->p->right;if(y->color==RED)x->p->color=BLACK;y->color=BLACK;x->p->p->color=RED;x=x->p->p;else//y->color==BLACKif(x==x->p->right)x=x->p;leftRotate(x);x->p->color=BLACK;x->p->p->color=RED;rightRotate(x->p->p);else//x->p==x->p->p->right(sameasabove,butwith“right”&“left”exchanged)Case1:uncleisREDCase2Case3RBInsert:Case1if(y->color==RED)x->p->color=BLACK;y->color=BLACK;x->p->p->color=RED;x=x->p->p;Case1:“uncle”isredInfiguresbelow,all’sareequal-black-heightsubtreesCADBCADBxynewxChangecolorsofsomenodes,preserving#4:alldownwardpathshaveequalb.h.Thewhileloopnowco
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 四年级信息技术上册 第七课 和电脑作文环境见面教案 川教版
- 2024-2025学年艺术疗愈在校园霸凌预防教学设计中的运用
- 《折线统计图》(教案)-2023-2024学年五年级下册数学人教版
- 2022年湖北襄阳中考满分作文《行走中的温暖》
- 2022年湖北恩施中考满分作文《在这头在那头》3
- 广东省阳东广雅学校高二信息技术 视频的采集与加工(一)教案
- 2023-2024学年五年级上册科学教科版1.7《制作一个潜望镜》(教案)
- 18 古诗三首 浪淘沙(其一)(教学设计)2024-2025学年统编版语文六年级上册
- 19《剃头大师》教案-2023-2024学年统编版语文三年级下册
- 智慧宿舍楼能源管理平台构建
- 人教版2024年新版七年级上册英语Starter Units 1-3综合测试卷(含答案)
- 四川航空介绍
- 电梯日管控、周排查、月调度内容表格
- DLT 1055-2021 火力发电厂汽轮机技术监督导则
- 红色国潮风欢度国庆汇报ppt
- 国家安全法课件
- 沪科版八年级数学上册131三角形边角关系(第一课时)教学设计
- 关于举行2015年攸县中小学教师课堂教学大赛决赛的
- 骨髓造血干细胞移植知情同意书
- 公对私转账借款合同范本
- 浙江大学top期刊850种
评论
0/150
提交评论