Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.
CS106B,Lecture20AdvancedBinaryTrees
Thisdocumentiscopyright(C)StanfordComputerScienceandAshleyTaylor,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyMartyStepp,ChrisGregg,KeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers
2
Plan for Today • DiscusshowtomakeaBSTclass(hint:usefulforMiniBrowser)• AdvancedBSTs
– Balancing– Red-BlackTrees– SplayTrees
• Non-BSTbinarytrees– Heaps– CartesianTrees
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.
ImplementingTreeSetandTreeMap
4
A BST set class //TreeSet.h//Asetofintegersrepresentedasabinarysearchtree.classTreeSet{members;...private:TreeNode*root;//NULLforanemptytree};
– ThisisbasicallyhowStanfordlibrary'sSetclassisimplemented.
– ClientcodetalkstotheTreeSet,nottothenodeobjectsinsideit.
– MembersofTreeSetcreateandmanipulatenodesandpointers.
40 81
9 41
17
6 29
root
5
Tree member template returnTypeTreeSet::functionName(parameters){helperName(root,parameters);}returnTypehelperName(TreeNode*node,parameters){...}• Treemethodsareoftenimplementedrecursivelyin2steps:
– apublicfunctionintendedtobecalledbytheclient– a"helper"functionthatacceptsapointertothenodetoprocess
– thepublicfunctiontypicallyjustcallsthehelperandpassesrootnode
6
Tree maps • Convertingatreesetintoatreemap:
– Eachtreenodewillstorebothakeyandavalue– treeisBST-orderedbyitskeys– keysmustbecomparable(havea<operator)forordering
structTreeMapNode{stringkey;intvalue;TreeMapNode*left;TreeMapNode*right;};
root
key ="Locke"val =51
key ="Jack"val =36
key ="Kate"val =28
key ="Sayid"val =36
key ="Sawyer"val =49
key ="Desmond"val =49
7
Tree map details • Eachtreesetoperationcorrespondstooneinthetreemap:
– add(value) → put(key,value)– contains(value) → containsKey(key)– remove(value) → remove(key)– mustaddanoperation: get(key)
– WhataboutcontainsValue?• WoulditscodebesimilartothecodeforcontainsKey?
root
key ="Locke"val =51
key ="Jack"val =36
key ="Kate"val =28
key ="Sayid"val =36
key ="Sawyer"val =49
key ="Desmond"val =49
8
Announcements • YoushouldbemostlydonewithCacheinMiniBrowser.LineManagerishard
• Homework3isgraded.Here'sthegradedistribution:
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.
BalancedTrees
10
Trees and balance • balancedtree:OnewhereforeverynodeR,theheightofR'ssubtreesdifferbyatmost1,andR'ssubtreesarealsobalanced.– Runtimeofadd/remove/containsarecloselyrelatedtoheight.– Balancedtree'sheightisroughlylog2N.UnbalancedisclosertoN.
19
7
146
9
84
root
height=4(balanced)
14
19
4
11
root
9
7
6height=7(unbalanced)
11
BST balance question • AddingthefollowingnodestoanemptyBSTinthefollowingorderproducesthetreeatright:22,9,34,18,3.
• Q:Whatisanorderinwhichwecouldhaveaddedthenodestoproduceanunbalancedtree?A.18,9,34,3,22B.9,18,3,34,22C.9,22,3,18,34D.noneoftheabove
22
9 34
183
12
AVL trees • AVLtree:Abinarysearchtreethatusesmodifiedaddandremoveoperationstostaybalancedasitselementschange.– basicidea:Whennodesareadded/removed,repairtreeshapeuntilbalanceisrestored.• rebalancingisO(1);overalltreemaintainsanO(logN)height
8
25
3
rotate
8
253
11 11
13
Red-Black trees • red-blacktree:Giveseachnodea"color"ofredorblack.(video)
– Rootisblack.Root'sdirectchildrenarered.Allleavesareblack.– Ifanodeisred,itschildrenmustallbeblack.– Everypathdownwardfromanodetothebottommustcontainthesamenumberof"black"nodes.
14
Splay trees • splaytree:Rotateseachelementyouaccesstothetop/root
– veryefficientwhenthatelementisaccessedagain(happensalot)– easytoimplementanddoesnotneedheightfieldineachnode
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.
Non-BSTBinaryTrees
16
Heaps
• Whatifyouwanttofindthek-smallestelementsinanunsortedVector?– Findthetop10studentsinaclass?
• Whatifyouwantedtoconstantlyinsertandremoveinsortedorder?– Modelahospitalemergencyroomwhereindividualsareseeninorderoftheirurgency
– PriorityQueue• What'sagoodchoice?
17
Heaps
• Idea:ifweuseaVector,ittakesalongtimetoinsertorremoveinsortedorder(orsearchtheVectorforthesmallestelement)
• Ifweuseabinarysearchtree,it'sfasttoinsertandremove(O(logN))butit'sslowtofindtheminimum/maximumelement(O(logN))
• Idea:useatree,butstoretheminimum/maximumelementastheroot– Treeshavelog(N)insertion/deletion– LookingattherootisO(1)
18
Heaps
• heap:Acompletebinarytreewithverticalordering:– min-heap:allchildrenmustbe≥parent'svalue– max-heap:allchildrenmustbe≤parent'svalue
– completetree:alllevelsarefullofchildrenexceptperhapsthebottomlevel,inwhichallexistingnodesaremaximallytotheleft.• Nicecorollary:heapsarealwaysbalanced
996040
8020
10
50 76
85
65
amin-heap
19
Heap enqueue • Whenaddingtoaheap,thevalueisfirstplacedatbottom-right.
– Torestoreheapordering,thenewlyaddedelementisshifted("bubbled")upthetreeuntilitreachesitsproperplace(wereachtheroot,ortheelementissmallerthanitsparent[min-heap]).
– Enqueue15atbottom-right;bubbleupuntilinorder.
996040
8020
10
50 700
85
65 15
992040
8015
10
50 700
85
65 60
20
15
60
20
Heap dequeue • Removetheroot,andreplaceitwiththefurthest-rightancestor• Torestoreheaporder,theimproperrootisshifted("bubbled")downthetreebyswappingwithitssmallerchild.– dequeueminof10;swapupbottom-rightleafof65;bubbledown.
996040
8020
65
74 50
85 996050
8040
20
74 65
85
10
65
40
20
50
40
20
65
50
40
20
21
Cartesian Trees
• Howwouldyouquicklyfindtheminimum/maximumelementinanrange?– Maximumelevationonahike?– Besttimetobuy/sellastockwithinacertainrangeoftimes?
22
Cartesian Trees
• Therootstorestheminimum(ormaximum)elementintheentirearray
• Theleftsubtreeisthentheminimum(ormaximum)elementintherangetotheleftoftheroot;therightsubtreeistheminimum(ormaximum)elementintherangetotherightoftheroot– Followsthemin-(ormax)-heapproperty:everyparentissmaller(orbigger)thanitschild
23
Cartesian Trees
• WhatwouldtheCartesiantreelooklikeforthisarrayifwe'retryingtofindtheminimumvalueinarange?
0 1 2 3 4 5 6 7 8 9 10
9 13 8 4 6 12 2 14 3 7 5
24
Cartesian Trees
• WhatwouldtheCartesiantreelooklikeforthisarrayifwe'retryingtofindtheminimumvalueinarange?
0 1 2 3 4 5 6 7 8 9 10
9 13 8 4 6 12 2 14 3 7 5
2
4
8 6
9 12
3
14 5
7
13
25
Cartesian Trees
• Howwouldwewritethefollowingfunction:findMinElemInRange(CartesianNode*node,intstart,intend)structCartesianNode{intindex;CartesianNode*left;CartesianNode*right;};
26
Exam • ThisexamwasalittleharderthanIintended.Youalldidreallywellandshowedalotofknowledgeofhardtopics.
• Commonmistakes:– BigOquestion,partc:theinnerforloopisactuallyO(1)– ADTtraceproblem:misreadingthefirstforloop– Recursivetrace:integerdivisionwiththeparameters,wrongindiceswithsubstring
– RecursiveBacktracking:modifiedparametersaftertherecursivecall,goingoutofboundsonthegrid,notdeclaringandreturningtheGrid,improperbasecases(returningtrue/falseorfailingtoprunethetree)
– ADTwrite,parta:badscopingforthevaluesoftheMapandOBOBforstringparsing
– ADTwrite,partb:incompletesubmissions(lowontime?)
27
Exam