General Trees. Tree Traversal Algorithms.
Transcript of General Trees. Tree Traversal Algorithms.
• GeneralTrees.• TreeTraversalAlgorithms.• BinaryTrees.
2CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia
• 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
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
• edgeoftreeTisapairofnodes(u,v)suchthatuistheparentofv,orviceversa.
• PathofTisasequenceofnodessuchthatanytwoconsecutivenodesinthesequenceformanedge.
• Atreeisordered ifthereisalinearorderingdefinedforthechildrenofeachnode
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 5© 2010 Goodrich, Tamassia
• 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
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 7© 2010 Goodrich, Tamassia
• 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
• 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
• 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
• 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
• 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
• 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
• 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
• 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
• 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
• 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
• 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
• 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
• 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
• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 21
• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.
A
B C
D
Internal nodes = 2External nodes = 2
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 22
• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.
A
B C
D
Internal nodes = 2External nodes = 3
E
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 23
• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.
A
B C
D
Internal nodes = 3External nodes = 3
E F
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 24
• Isabinarytreewherethenumberofexternalnodesis1morethanthenumberofinternalnodes.
A
B C
D
Internal nodes = 3External nodes = 4
E F G
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 25
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
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
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
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
• 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
• 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
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 32© 2010 Goodrich, Tamassia
• 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
• Binarytreesareexcellentdatastructuresforsearchinglargeamountsofinformation.
• Whenusedtofacilitatesearches,abinarytreeiscalledabinarysearchtree.
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 34
• 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
• Therearethreecommonmethodsfortraversingabinarytreeandprocessingthevalueofeachnode:• Pre-order• In-order• Post-order
• Eachofthesemethodsisbestimplementedasarecursivefunction.
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 36
• 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
• Insertthefollowingitemsintoabinarysearchtree.50,25,75,12,30,67,88,6,13,65,68
• DrawthebinarytreeandprinttheitemsusingPre-ordertraversal.
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 38
• 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
• 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
• 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
• 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
• 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
• Afterdeletinganitem,theresultingbinarytreemustbeabinarysearchtree.1. Findthenodetobedeleted.2. Deletethenodefromthetree.
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 44
• 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
• 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
• 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
• 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
• 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
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
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
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
CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 53