cs 106b, lecture 20 advanced binary trees...avl trees • avl tree: a binary search tree that uses...

27
CS 106B, Lecture 20 Advanced Binary Trees This document is copyright (C) Stanford Computer Science and Ashley Taylor, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Marty Stepp, Chris Gregg, Keith Schwarz, Julie Zelenski, Jerry Cain, Eric Roberts, Mehran Sahami, Stuart Reges, Cynthia Lee, and others

Upload: others

Post on 22-Apr-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 2: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

2

Plan for Today • DiscusshowtomakeaBSTclass(hint:usefulforMiniBrowser)• AdvancedBSTs

–  Balancing–  Red-BlackTrees–  SplayTrees

• Non-BSTbinarytrees– Heaps–  CartesianTrees

Page 3: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.

ImplementingTreeSetandTreeMap

Page 4: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 5: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

5

Tree member template returnTypeTreeSet::functionName(parameters){helperName(root,parameters);}returnTypehelperName(TreeNode*node,parameters){...}•  Treemethodsareoftenimplementedrecursivelyin2steps:

–  apublicfunctionintendedtobecalledbytheclient–  a"helper"functionthatacceptsapointertothenodetoprocess

–  thepublicfunctiontypicallyjustcallsthehelperandpassesrootnode

Page 6: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 7: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 8: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

8

Announcements • YoushouldbemostlydonewithCacheinMiniBrowser.LineManagerishard

• Homework3isgraded.Here'sthegradedistribution:

Page 9: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.

BalancedTrees

Page 10: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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)

Page 11: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 12: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

12

AVL trees • AVLtree:Abinarysearchtreethatusesmodifiedaddandremoveoperationstostaybalancedasitselementschange.–  basicidea:Whennodesareadded/removed,repairtreeshapeuntilbalanceisrestored.• rebalancingisO(1);overalltreemaintainsanO(logN)height

8

25

3

rotate

8

253

11 11

Page 13: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

13

Red-Black trees •  red-blacktree:Giveseachnodea"color"ofredorblack.(video)

–  Rootisblack.Root'sdirectchildrenarered.Allleavesareblack.–  Ifanodeisred,itschildrenmustallbeblack.–  Everypathdownwardfromanodetothebottommustcontainthesamenumberof"black"nodes.

Page 14: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

14

Splay trees • splaytree:Rotateseachelementyouaccesstothetop/root

–  veryefficientwhenthatelementisaccessedagain(happensalot)–  easytoimplementanddoesnotneedheightfieldineachnode

Page 15: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,JulieZelenski,JerryCain,EricRoberts,MehranSahami,StuartReges,CynthiaLee,andothers.

Non-BSTBinaryTrees

Page 16: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

16

Heaps

• Whatifyouwanttofindthek-smallestelementsinanunsortedVector?–  Findthetop10studentsinaclass?

• Whatifyouwantedtoconstantlyinsertandremoveinsortedorder?– Modelahospitalemergencyroomwhereindividualsareseeninorderoftheirurgency

–  PriorityQueue• What'sagoodchoice?

Page 17: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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)

Page 18: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 19: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 20: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 21: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

21

Cartesian Trees

• Howwouldyouquicklyfindtheminimum/maximumelementinanrange?– Maximumelevationonahike?–  Besttimetobuy/sellastockwithinacertainrangeoftimes?

Page 22: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

22

Cartesian Trees

• Therootstorestheminimum(ormaximum)elementintheentirearray

• Theleftsubtreeisthentheminimum(ormaximum)elementintherangetotheleftoftheroot;therightsubtreeistheminimum(ormaximum)elementintherangetotherightoftheroot–  Followsthemin-(ormax)-heapproperty:everyparentissmaller(orbigger)thanitschild

Page 23: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 24: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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

Page 25: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

25

Cartesian Trees

• Howwouldwewritethefollowingfunction:findMinElemInRange(CartesianNode*node,intstart,intend)structCartesianNode{intindex;CartesianNode*left;CartesianNode*right;};

Page 26: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

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?)

Page 27: CS 106B, Lecture 20 Advanced Binary Trees...AVL trees • AVL tree: A binary search tree that uses modified add and remove operations to stay balanced as its elements change. – basic

27

Exam