CSE 373: Data Structures and Algorithms · Pros and Cons of AVL Trees Arguments for AVL trees: 1....
Transcript of CSE 373: Data Structures and Algorithms · Pros and Cons of AVL Trees Arguments for AVL trees: 1....
Instructor:LiliandeGreefQuarter:Summer2017
CSE373:DataStructuresandAlgorithmsLecture11:FinishAVLTrees;PriorityQueues;BinaryHeaps
Announcements
• ChangestoOfficeHours:fromnowon…• NomoreWednesdaymorning&shorterWednesdayafternoonofficehours• New Thursdayofficehours!• Kyle’sWednesdayhourisnow1:30-2:30pm• Ben’sofficehoursisnowThursday1:00-3:00pm
• AVLTreeHeight• Insection,computedthatminimum#nodesinAVLtreeofacertainheightisS(h)=1+S(h-1)+S(h-2)whereh=heightoftree• Postedaproofnexttotheselectureslidesonlineforyourperusal
Announcements
• Midterm• NextFriday!(atusualclasstime&location)• Everythingwecoverinclassuntilexamdateisfairgame(minusclearly-marked“bonusmaterial”).Thatincludesnextweek’smaterial!
• Today’shw3duedatedesignedtogiveyoutimetostudy.
• CourseFeedback• Headsup:officialUW-mediatedcoursefeedbacksessionforpartofWednesday• Alsowanttobetterunderstandananonymousconcernoncoursepacing→ Poll
TheAVLTreeDataStructure
AnAVLtreeisaself-balancingbinarysearchtree.
Structuralproperties1. Binarytreeproperty(sameasBST)2. Order property(sameasforBST)
3. Balancecondition:balanceofeverynodeisbetween-1and1
wherebalance(node)=height(node.left)– height(node.right)
Result:Worst-case depthisO(logn)
Case#3:Right-LeftCase(afteronerotation)
(FiguresbyMelissaO’Neill,reprintedwithherpermissiontoLilian)
rightrotate
Case#3:Right-LeftCase(aftertworotations)
(FiguresbyMelissaO’Neill,reprintedwithherpermissiontoLilian)
rightrotate
leftrotate
Awaytorememberit:Movedtograndparent’sposition.PuteverythingelseintheironlylegalpositionsforaBST.
Practicetime!ExampleofCase#4
A)
5010
8030
60
10
30
42
8050
60
10
30
50
8042
60
10
30
50
8042
60
42
10
30
8060
50
B) C) D)
WhichofthefollowingistheupdatedAVLtreeafterinserting42?
StartingwiththisAVLtree:
Practicetime!ExampleofCase#4
5010
8030
60 WhichofthefollowingistheupdatedAVLtreeafterinserting42?
StartingwiththisAVLtree:
Whatrotationsdidwedo?What’sthenameofthiscase?
Insert,summarized
• InsertasinourgenericBST• Checkbackuppathforimbalance,whichwillbe1of4cases:
• Node’sleft-left grandchildistootall• Node’s left-rightgrandchildistootall• Node’sright-left grandchildistootall• Node’sright-rightgrandchildistootall
• Onlyoccursbecause• Aftertheappropriatesingleordoublerotation,thesmallest-unbalancedsubtreehasthesameheightasbeforetheinsertion• Soallancestorsarenowbalanced
14
one case tree was balanced before insert
AVLTreeEfficiency
• Worst-casecomplexityoffind:
• Worst-casecomplexityofinsert:
• Worst-casecomplexityofbuildTree:
Takessomemorerotationactiontohandledelete…
ProsandConsofAVLTreesArgumentsforAVLtrees:
1. Alloperationslogarithmicworst-casebecausetreesarealways balanced2. Heightbalancingaddsnomorethanaconstantfactortothespeedof
insert anddelete
ArgumentsagainstAVLtrees:
1. Difficulttoprogram&debug[butdoneonceinalibrary!]2. Morespaceforheightfield3. Asymptoticallyfasterbutrebalancingtakesalittletime4. Ifamortized logarithmictimeisenough,usesplaytrees(alsointhetext,
notcoveredinthisclass)
LotsofcoolSelf-BalancingBSTsoutthere!
Popularself-balancingBSTsinclude:• AVLtree• Splaytree• 2-3tree• AAtree• Red-blacktree• Scapegoattree• Treap(Fromhttps://en.wikipedia.org/wiki/Self-balancing_binary_search_tree#Implementations)
(Notcoveredinthisclass,butseveralareinthetextbookandallofthemareonline!)
WrappingUp:HashTablevsBSTDictionary
HashTableadvantages:
BSTadvantages:• Cangetkeysinsortedorderwithoutmuchextraeffort• Samefororderingstatistics,findingclosestelements,rangequeries• Easiertoimplementifdon’thavehashfunction(whicharehard!).• CanguaranteeO(logn)worst-casetime,whereashashtablesareO(1)average time.
AnIntroductoryExample…
GillBates,theCEOofthesoftwarecompanyMillisoft,builtarobotsecretarytomanageherhundredsofemails.Duringtheday,Batesonlywantstolookatafewemailseverynowandthensoshecanstayfocused.Therobotsecretarysendsherthemostimportantemailseachtime.Todoso,heassignseachemailapriority whenhegetsthemandonlysendsBatesthehighestpriority emailsuponrequest.
Allofyourcomputerserversareonfire!Priority:
Here’sareminderforourmeetingin2months.Priority:
PriorityQueueADTApriorityqueue holdscompare-abledata
• Likedictionaries,weneedtocompareitems• Givenx andy,isx lessthan,equalto,orgreaterthany• Meaningoftheorderingcandependonyourdata
• Thedatatypicallyhastwofields:• We’llnowuseintegersforexamples,butcanuseothertypes/objectsforprioritiestoo!
newemail highestpriorityemail
71812
23
345
156 2
Inourintroductoryexample:
PriorityQueueADTMeaning:• Apriorityqueue holdscompare-abledata• Keyproperty:
Operations:
71812
23
345
156 2