General Trees. Tree Traversal Algorithms.

53

Transcript of General Trees. Tree Traversal Algorithms.

Page 1: General Trees. Tree Traversal Algorithms.
Page 2: General Trees. Tree Traversal Algorithms.

• GeneralTrees.• TreeTraversalAlgorithms.• BinaryTrees.

2CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia

Page 3: General Trees. Tree Traversal Algorithms.

• Incomputerscience,atreeisanabstractmodelofahierarchicalstructure.

• Atreeconsistsofnodeswithaparent-childrelation.

• Applications:• Organizationcharts.• Filesystems.• Programmingenvironments.

Computers”R”Us

Sales R&DManufacturing

Laptops DesktopsUS International

Europe Asia Canada

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 3© 2010 Goodrich, Tamassia

Page 4: General Trees. Tree Traversal Algorithms.

Subtree

• Root:nodewithoutparent(A)• Internalnode: nodewithatleastonechild(A,B,C,F)

• Externalnode(a.k.a.leaf):nodewithoutchildren(E,I,J,K,G,H,D)

• Ancestorsofanode:parent,grandparent,grand-grandparent,etc.

• Depthofanode:numberofancestors

• Heightofatree:maximumdepthofanynode(3)

• Descendantofanode:child,grandchild,grand-grandchild,etc.

A

B DC

G HE F

I J K

• Subtree:treeconsistingofanodeanditsdescendants.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 4© 2010 Goodrich, Tamassia

Page 5: General Trees. Tree Traversal Algorithms.

• edgeoftreeTisapairofnodes(u,v)suchthatuistheparentofv,orviceversa.

• PathofTisasequenceofnodessuchthatanytwoconsecutivenodesinthesequenceformanedge.

• Atreeisordered ifthereisalinearorderingdefinedforthechildrenofeachnode

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 5© 2010 Goodrich, Tamassia

Page 6: General Trees. Tree Traversal Algorithms.

• Weusepositions(nodes)toabstractnodes.• getElement(): Returntheobjectstoredatthisposition.

• Genericmethods:• integergetSize()• boolean isEmpty()• Iterator iterator()• Iterable positions()

• Accessor methods:• positiongetRoot()• positiongetThisParent(p)• Iterable children(p)

• Querymethods:• boolean isInternal(p)• boolean isExternal(p)• boolean isRoot(p)

• Updatemethod:• elementreplace(p,o)

• AdditionalupdatemethodsmaybedefinedbydatastructuresimplementingtheTreeADT.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 6© 2010 Goodrich, Tamassia

Page 7: General Trees. Tree Traversal Algorithms.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 7© 2010 Goodrich, Tamassia

Page 8: General Trees. Tree Traversal Algorithms.

• LetvbeanodeofatreeT.Thedepth ofv isthenumberofancestorsofv,excludingv itself.• Ifv istheroot,thenthedepthofv is0• Otherwise,thedepthofv isoneplusthedepthoftheparentofv.

• Therunningtimeofalgorithmdepth(T,v)isO(dv),wheredvdenotesthedepthofthenodev inthetreeT.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 8

Algorithm depth(T,v):if v istherootofTthen

return 0else

return 1+depth(T,w),wherewistheparentofv inT

© 2010 Goodrich, Tamassia

Page 9: General Trees. Tree Traversal Algorithms.

• Atreeisadatastructurewhichstoreselementsinparent-child relationship.

A

B C

D E F G H

Root node

Internal nodes

Leaf nodes (External nodes)

Siblings

Siblings

Siblings

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 9

Page 10: General Trees. Tree Traversal Algorithms.

• Depth:thenumberofancestorsofthatnode(excludingitself).

• Height: themaximumdepthofanexternalnodeofthetree/subtree.

A

B C

D E F G H

I

Depth(D) = ?Depth(D) = 1Depth(D) = 2

Depth(I) = ?Depth(I) = 3

Height = MAX[ Depth(A), Depth(B), Depth(C), Depth(D), Depth(E), Depth(F), Depth(G), Depth(H), Depth(I) ]

Height = MAX[ 0, 1, 1, 2, 2, 2, 2, 2, 3 ] = 3CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 10

Page 11: General Trees. Tree Traversal Algorithms.

• Theheight ofanodev inatreeTiscanbecalculatedusingthedepth algorithm.

• algorithmheight1 runsinO(n2)time

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 11

Algorithmheight1(T):h←0for eachvertexv inTdo

if v isanexternalnodeinTthenh←max(h,depth(T,v))

return h

© 2010 Goodrich, Tamassia

Page 12: General Trees. Tree Traversal Algorithms.

• Theheight ofanodev inatreeTisalsodefinedrecursively:• Ifv isanexternalnode,thentheheightofv is0• Otherwise,theheightofv isoneplusthemaximumheightofachildofv.

• algorithmheight1 runsinO(n)timeCPSC 3200 University of Tennessee at Chattanooga – Summer 2013 12

Algorithmheight2(T,v):ifv isanexternalnodeinTthen

return 0else

h←0for eachchildwofv inTdo

h←max(h,height2(T,w))return 1+h

© 2010 Goodrich, Tamassia

Page 13: General Trees. Tree Traversal Algorithms.

• Atraversalvisitsthenodesofatreeinasystematicmanner.

• Inapreorder traversal,anodeisvisitedbeforeitsdescendants.

• Application:printastructureddocument.

Make Money Fast!

1. Motivations References2. Methods

2.1 StockFraud

2.2 PonziScheme1.1 Greed 1.2 Avidity

2.3 BankRobbery

1

2

3

5

4 6 7 8

9

Algorithm preOrder(v)visit(v)for each childw ofv

preorder (w)

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 13© 2010 Goodrich, Tamassia

Page 14: General Trees. Tree Traversal Algorithms.

• Inapostorder traversal,anodeisvisitedafteritsdescendants.

• Application:computespaceusedbyfilesinadirectoryanditssubdirectories.

Algorithm postOrder(v)for each childw ofv

postOrder (w)visit(v)

cs16/

homeworks/todo.txt1Kprograms/

DDR.java10K

Stocks.java25K

h1c.doc3K

h1nc.doc2K

Robot.java20K

9

3

1

7

2 4 5 6

8

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 14© 2010 Goodrich, Tamassia

Page 15: General Trees. Tree Traversal Algorithms.

• Theorderinwhichthenodesarevisitedduringatreetraversalcanbeeasilydeterminedbyimaginingthereisa“flag”attachedtoeachnode,asfollows:

• Totraversethetree,collecttheflags:

preorder inorder postorder

A

B C

D E F G

A

B C

D E F G

A

B C

D E F G

A B D E C F G D B E A F C G D E B F G C ACPSC 3200 University of Tennessee at Chattanooga – Summer 2013 15

Page 16: General Trees. Tree Traversal Algorithms.

• Theothertraversalsarethereverseofthesethreestandardones• Thatis,therightsubtree istraversedbeforetheleftsubtree istraversed

• Reversepreorder: root,rightsubtree,leftsubtree.• Reverseinorder:rightsubtree,root,leftsubtree.• Reversepostorder: rightsubtree,leftsubtree,root.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 16

Page 17: General Trees. Tree Traversal Algorithms.

• Abinarytreeisatreewiththefollowingproperties:• Eachinternalnodehasatmosttwochildren (exactlytwoforproperbinarytrees).• Thechildrenofanodeareanorderedpair.

• Wecallthechildrenofaninternalnodeleftchild andrightchild.

• Alternativerecursivedefinition:abinarytreeiseither• atreeconsistingofasinglenode,or• atreewhoseroothasanorderedpairofchildren,eachofwhichisabinarytree.

A

B C

F GD E

H I

Applications:• arithmeticexpressions.• decisionprocesses.• searching.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 17© 2010 Goodrich, Tamassia

Page 18: General Trees. Tree Traversal Algorithms.

• Abinarytreeisbalancedifeverylevelabovethelowestis“full”(contains2h nodes)

• Inmostapplications,areasonablybalancedbinarytreeisdesirable.

a

b c

d e f g

h i jA balanced binary tree

a

b

c

d

e

f

g h

i jAn unbalanced binary tree

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 18

Page 19: General Trees. Tree Traversal Algorithms.

• Binarytreeassociatedwithadecisionprocess• internalnodes:questionswithyes/noanswer• externalnodes:decisions

• Example:diningdecision

Want a fast meal?

How about coffee? On expense account?

Starbucks Spike’s Al Forno Café Paragon

Yes No

Yes No Yes No

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 19© 2010 Goodrich, Tamassia

Page 20: General Trees. Tree Traversal Algorithms.

• Binarytreeassociatedwithanarithmeticexpression• internalnodes:operators• externalnodes:operands

• Example: arithmeticexpressiontreefortheexpression(2´ (a- 1)+ (3´ b))

+

´´

-2

a 1

3 b

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 20© 2010 Goodrich, Tamassia

Page 21: General Trees. Tree Traversal Algorithms.

• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 21

Page 22: General Trees. Tree Traversal Algorithms.

• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.

A

B C

D

Internal nodes = 2External nodes = 2

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 22

Page 23: General Trees. Tree Traversal Algorithms.

• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.

A

B C

D

Internal nodes = 2External nodes = 3

E

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 23

Page 24: General Trees. Tree Traversal Algorithms.

• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.

A

B C

D

Internal nodes = 3External nodes = 3

E F

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 24

Page 25: General Trees. Tree Traversal Algorithms.

• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.

A

B C

D

Internal nodes = 3External nodes = 4

E F G

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 25

Page 26: General Trees. Tree Traversal Algorithms.

Worstcase: Thetreehavingtheminimumnumberofexternalandinternalnodes.

Bestcase: Thetreehavingthemaximumnumberofexternalandinternalnodes.

1.Thenumberofexternalnodesisatleasth+1 andatmost2h

Ex:h=3

External nodes = 3+1 = 4

External nodes = 23 = 8

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 26

Page 27: General Trees. Tree Traversal Algorithms.

2.Thenumberofinternalnodesisatleasth andatmost2h-1Ex:h=3Worstcase: Thetreehavingtheminimumnumberofexternalandinternalnodes.

Bestcase: Thetreehavingthemaximumnumberofexternalandinternalnodes.

Internal nodes = 3

Internal nodes = 23 -1=7

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 27

Page 28: General Trees. Tree Traversal Algorithms.

3.Thenumberofnodesisatleast2h+1 andatmost2h+1 -1Ex:h=3

Internal nodes = 3External nodes = 4

----------------------------Internal + External = 2*3 +1 = 7

Internal nodes = 7External nodes = 8-----------------------

Internal + External = 23+1 – 1 = 15

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 28

Page 29: General Trees. Tree Traversal Algorithms.

4.Theheightisatleastlog(n+1)-1andatmost(n-1)/2

Number of nodes = 7h = 3

Number of nodes = 15h = 3

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 29

Page 30: General Trees. Tree Traversal Algorithms.

• TheBinaryTree ADTextends theTreeADT,i.e.,itinheritsallthemethodsoftheTreeADT.

• Additionalmethods:• positiongetThisLeft(p)• positiongetThisRightight(p)• boolean hasLeft(p)• boolean hasRight(p)

• UpdatemethodsmaybedefinedbydatastructuresimplementingtheBinaryTree ADT.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 30© 2010 Goodrich, Tamassia

Page 31: General Trees. Tree Traversal Algorithms.

• Anodeisrepresentedbyanobjectstoring• Element• Parentnode• Leftchildnode• Rightchildnode

• NodeobjectsimplementthePositionADT

B

DA

C E

Æ Æ

Æ Æ Æ Æ

B

A D

C E

Æ

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 31© 2010 Goodrich, Tamassia

Page 32: General Trees. Tree Traversal Algorithms.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 32© 2010 Goodrich, Tamassia

Page 33: General Trees. Tree Traversal Algorithms.

• addRoot(e): Createandreturnanewnoderstoringelementeandmakertherootofthetree;anerroroccursifthetreeisnotempty.

• insertLeft(v,e): Createandreturnanewnodewstoringelemente,addwasthethe leftchildofvandreturnw;anerroroccursifvalreadyhasaleftchild.

• insertRight(v,e): Createandreturnanewnodezstoringelemente,addzasthethe rightchildofvandreturnz;anerroroccursifvalreadyhasarightchild.

• remove(v): Removenodev,replaceitwithitschild,ifany,andreturntheelementstoredatv;anerroroccursifvhastwochildren.

• attach(v,T1,T2): AttachT1andT2,respectively,astheleftandrightsubtrees oftheexternalnodev;anerrorconditionoccursifv isnotexternal.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 33© 2010 Goodrich, Tamassia

Page 34: General Trees. Tree Traversal Algorithms.

• Binarytreesareexcellentdatastructuresforsearchinglargeamountsofinformation.

• Whenusedtofacilitatesearches,abinarytreeiscalledabinarysearchtree.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 34

Page 35: General Trees. Tree Traversal Algorithms.

• Abinarysearchtree(BST)isabinarytreeinwhich:• Elementsinleft subtree aresmaller thanthecurrentnode.• Elementsinright subtree aregreater thanthecurrentnode.

10

7 12

5 9 11 25

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 35

Page 36: General Trees. Tree Traversal Algorithms.

• Therearethreecommonmethodsfortraversingabinarytreeandprocessingthevalueofeachnode:• Pre-order• In-order• Post-order

• Eachofthesemethodsisbestimplementedasarecursivefunction.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 36

Page 37: General Trees. Tree Traversal Algorithms.

• Pre-order: Nodea Lefta Right

A

B C

D E F G

A B D E C F GCPSC 3200 University of Tennessee at Chattanooga – Summer 2013 37

Page 38: General Trees. Tree Traversal Algorithms.

• Insertthefollowingitemsintoabinarysearchtree.50,25,75,12,30,67,88,6,13,65,68

• DrawthebinarytreeandprinttheitemsusingPre-ordertraversal.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 38

Page 39: General Trees. Tree Traversal Algorithms.

• In-order: Lefta Nodea Right

A

B C

D E F G

D B E A F C GCPSC 3200 University of Tennessee at Chattanooga – Summer 2013 39

Page 40: General Trees. Tree Traversal Algorithms.

• Fromthepreviousexercise,printthetree’snodesusingIn-ordertraversal.

50

25 75

12 30 67 88

6 13 65 68

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 40

Page 41: General Trees. Tree Traversal Algorithms.

• Post-order: Lefta Righta Node

A

B C

D E F G

D E B F G C ACPSC 3200 University of Tennessee at Chattanooga – Summer 2013 41

Page 42: General Trees. Tree Traversal Algorithms.

• Fromthepreviousexercise,printthetree’snodesusingPost-ordertraversal.

50

25 75

12 30 67 88

6 13 65 68

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 42

Page 43: General Trees. Tree Traversal Algorithms.

• Inaninorder traversalanodeisvisitedafteritsleftsubtreeandbeforeitsrightsubtree

• Application:drawabinarytree• x(v)=inorder rankofv• y(v)=depthofv

Algorithm inOrder(v)if hasLeft (v)

inOrder (left (v))visit(v)if hasRight (v)

inOrder (right (v))

3

1

2

5

6

7 9

8

4

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 43© 2010 Goodrich, Tamassia

Page 44: General Trees. Tree Traversal Algorithms.

• Afterdeletinganitem,theresultingbinarytreemustbeabinarysearchtree.1. Findthenodetobedeleted.2. Deletethenodefromthetree.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 44

Page 45: General Trees. Tree Traversal Algorithms.

• Thenodetobedeletedhasnoleftandrightsubtree (thenodetobedeletedisaleaf).

60

50 70

30 53 65 80

51 57 61 67 79 95

delete(30)

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 45

Page 46: General Trees. Tree Traversal Algorithms.

• Thenodetobedeletedhasnoleftsubtree (theleftsubtreeisemptybutithasanonemptyrightsubtree).

60

50 70

30 53 65 80

35 51 57 61 67 79 95

delete(30)

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 46

Page 47: General Trees. Tree Traversal Algorithms.

• Thenodetobedeletedhasnorightsubtree (therightsubtree isemptybutithasanonemptyleftsubtree).

60

50 70

30 53 65 80

25 35 51 57 61 67 79

delete(80)

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 47

Page 48: General Trees. Tree Traversal Algorithms.

• Thenodetobedeletedhasnonemptyleftandrightsubtree.

60

50 70

30 53 65 80

25 35 51 57 61 67 79 95

delete(70)

79

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 48

Page 49: General Trees. Tree Traversal Algorithms.

• Thenodetobedeletedhasnonemptyleftandrightsubtree.

60

50 70

30 53 65 80

25 35 51 57 61 67 79 95

delete(70)

67

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 49

Page 50: General Trees. Tree Traversal Algorithms.

50

• Binarysearchcanperformoperationsget,floorEntry andceilingEntry onanorderedmapimplementedbymeansofanarray-basedsequence,sortedbykey• similartothehigh-lowgame• ateachstep,thenumberofcandidateitemsishalved• terminatesafterO(logn)steps

• Example:find(7)1 3 4 5 7 8 9 11 14 16 18 19

1 3 4 5 7 8 9 11 14 16 18 19

1 3 4 5 7 8 9 11 14 16 18 19

1 3 4 5 7 8 9 11 14 16 18 19

0

0

0

0

ml h

ml h

ml h

l=m =hCPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia

Page 51: General Trees. Tree Traversal Algorithms.

51

• Abinarysearchtreeisabinarytreestoringkeys(orkey-valueentries)atitsinternalnodesandsatisfyingthefollowingproperty:• Letu,v,andw bethreenodessuchthatu isintheleftsubtree ofv andw isintherightsubtreeofv.Wehavekey(u)£ key(v)£ key(w)

• Externalnodesdonotstoreitems.

• Aninorder traversalofabinarysearchtreesvisitsthekeysinincreasingorder.

6

92

41 8

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia

Page 52: General Trees. Tree Traversal Algorithms.

52

• Tosearchforakeyk,wetraceadownwardpathstartingattheroot.

• Thenextnodevisiteddependsonthecomparisonofkwiththekeyofthecurrentnode.

• Ifwereachaleaf,thekeyisnotfound.

• Example:get(4):• CallTreeSearch(4,root)

Algorithm TreeSearch(k, v)if T.isExternal (v)return v

ifk < key(v)return TreeSearch(k, T.left(v))

elseifk = key(v)return v

else {k > key(v)}return TreeSearch(k, T.right(v))

6

92

41 8

<

>

=

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia

Page 53: General Trees. Tree Traversal Algorithms.

CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 53