CSC311: Data Structures 1 Chapter 7: Trees Objectives: Introduce general tree structure and Tree ADT...
-
date post
21-Dec-2015 -
Category
Documents
-
view
214 -
download
0
Transcript of CSC311: Data Structures 1 Chapter 7: Trees Objectives: Introduce general tree structure and Tree ADT...
CSC311: Data StructuresCSC311: Data Structures 11
Chapter 7: TreesChapter 7: TreesObjectives:Objectives:
Introduce general tree structure and Introduce general tree structure and Tree ADTTree ADT
Discuss the depth and height of treesDiscuss the depth and height of trees Introduce the tree traversal algorithms Introduce the tree traversal algorithms Specialize to binary treesSpecialize to binary trees Implement binary trees with linked Implement binary trees with linked
structure and array-list structurestructure and array-list structure Introduce the Template Method PatternIntroduce the Template Method Pattern
TreesTrees CSC311: Data StructuresCSC311: Data Structures 22
What is a TreeWhat is a TreeIn computer science, a In computer science, a tree is an abstract tree is an abstract model of a hierarchical model of a hierarchical structurestructure
A tree consists of nodes A tree consists of nodes with a parent-child with a parent-child relationrelation
Applications:Applications:– Organization chartsOrganization charts– File systemsFile systems– Programming Programming
environmentsenvironments
Computers”R”Us
Sales R&DManufacturing
Laptops DesktopsUS International
Europe Asia Canada
TreesTrees CSC311: Data StructuresCSC311: Data Structures 33subtree
Tree TerminologyTree TerminologyRoot: node without parent (A)Root: node without parent (A)Internal node: node with at Internal node: node with at least one child (A, B, C, F)least one child (A, B, C, F)External node (a.k.a. leaf ): External node (a.k.a. leaf ): node without children (E, I, J, K, node without children (E, I, J, K, G, H, D)G, H, D)Ancestors of a node: parent, Ancestors of a node: parent, grandparent, grand-grandparent, grand-grandparent, etc.grandparent, etc.Depth of a node: number of Depth of a node: number of ancestorsancestorsHeight of a tree: maximum Height of a tree: maximum depth of any node (3)depth of any node (3)Descendant of a node: child, Descendant of a node: child, grandchild, grand-grandchild, grandchild, grand-grandchild, etc.etc.
A
B DC
G HE F
I J K
Subtree: tree Subtree: tree consisting of a node consisting of a node and its descendantsand its descendants
TreesTrees CSC311: Data StructuresCSC311: Data Structures 44
Tree ADT Tree ADT We use positions to We use positions to abstract nodesabstract nodes
Generic methods:Generic methods:– integer integer sizesize()()– boolean boolean isEmptyisEmpty()()– Iterator Iterator iteratoriterator()()– Iterator Iterator positionspositions()()
Accessor methods:Accessor methods:– position position rootroot()()– position position parentparent(p)(p)– positionIterator positionIterator
childrenchildren(p)(p)
Query methods:Query methods:– boolean boolean isInternalisInternal(p)(p)– boolean boolean isExternalisExternal(p)(p)– boolean boolean isRootisRoot(p)(p)
Update method:Update method:– object object replace replace (p, o)(p, o)
Additional update Additional update methods may be defined methods may be defined by data structures by data structures implementing the Tree implementing the Tree ADTADT
TreesTrees CSC311: Data StructuresCSC311: Data Structures 55
Depth of a NodeDepth of a Node
The depth of a The depth of a node v in a tree T node v in a tree T is defined as:is defined as:– If v is the root, then If v is the root, then
its depth is 0;its depth is 0;– Otherwise, its Otherwise, its
depth is one plus depth is one plus the depth of its the depth of its parent parent
Algorithm depth(T, v)Algorithm depth(T, v)Input: Tree T and a node vInput: Tree T and a node v
Output: an integer that is the Output: an integer that is the depth of v in Tdepth of v in T
If v is the root of T thenIf v is the root of T then
return 0return 0
ElseElse
return 1 + depth(T, parent(v))return 1 + depth(T, parent(v))
TreesTrees CSC311: Data StructuresCSC311: Data Structures 66
Height of a NodeHeight of a Node
The height of a The height of a node v in a tree T node v in a tree T is defined as:is defined as:– If v is an external, If v is an external,
then its height is 0;then its height is 0;– Otherwise, its Otherwise, its
height is one plus height is one plus the maximum the maximum height of its height of its children children
Algorithm height(T, v)Algorithm height(T, v)Input: Tree T and a node vInput: Tree T and a node v
Output: an integer that is the Output: an integer that is the height of v in Theight of v in T
If v is an external of T thenIf v is an external of T then
return 0return 0
ElseElse
hh00
for each child w of v in T dofor each child w of v in T do
hhmax(h, height(T,w))max(h, height(T,w))
return 1+hreturn 1+h
TreesTrees CSC311: Data StructuresCSC311: Data Structures 77
Features on HeightFeatures on Height
1.1. The height of a nonempty tree T is The height of a nonempty tree T is equal to the maximum depth of an equal to the maximum depth of an external node of Texternal node of T
2.2. Let T be a tree with n nodes, and let Let T be a tree with n nodes, and let ccvv denote the number if children of denote the number if children of a node v of T. The summing over a node v of T. The summing over the vertices in T, the vertices in T, vvccvv=n-1.=n-1.
TreesTrees CSC311: Data StructuresCSC311: Data Structures 88
Preorder TraversalPreorder TraversalA traversal visits the nodes of A traversal visits the nodes of a tree in a systematic mannera tree in a systematic manner
In a preorder traversal, a In a preorder traversal, a node is visited before its node is visited before its descendants descendants
Application: print a structured Application: print a structured documentdocument
Make Money Fast!
1. Motivations References2. Methods
2.1 StockFraud
2.2 PonziScheme
1.1 Greed 1.2 Avidity2.3 BankRobbery
1
2
3
5
4 6 7 8
9
Algorithm preOrder(v)visit(v)for each child w of v
preorder (w)
TreesTrees CSC311: Data StructuresCSC311: Data Structures 99
Postorder TraversalPostorder TraversalIn a postorder traversal, a In a postorder traversal, a node is visited after its node is visited after its descendantsdescendants
Application: compute space Application: compute space used by files in a directory used by files in a directory and its subdirectoriesand its subdirectories
Algorithm postOrder(v)for each child w of v
postOrder (w)visit(v)
cs16/
homeworks/todo.txt
1Kprograms/
DDR.java10K
Stocks.java25K
h1c.doc3K
h1nc.doc2K
Robot.java20K
9
3
1
7
2 4 5 6
8
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1010
Binary TreesBinary TreesA binary tree is a tree with the A binary tree is a tree with the following properties:following properties:– Each internal node has at most Each internal node has at most
two children (exactly two for two children (exactly two for properproper binary trees) binary trees)
– The children of a node are an The children of a node are an ordered pairordered pair
We call the children of an We call the children of an internal node left child and right internal node left child and right childchildAlternative recursive definition: Alternative recursive definition: a binary tree is eithera binary tree is either– a tree consisting of a single a tree consisting of a single
node, ornode, or– a tree whose root has an a tree whose root has an
ordered pair of children, each of ordered pair of children, each of which is a binary treewhich is a binary tree
Applications:Applications:– arithmetic arithmetic
expressionsexpressions– decision processesdecision processes– searchingsearching
A
B C
F GD E
H I
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1111
Arithmetic Expression TreeArithmetic Expression TreeBinary tree associated with an arithmetic Binary tree associated with an arithmetic expressionexpression– internal nodes: operatorsinternal nodes: operators– external nodes: operandsexternal nodes: operands
Example: arithmetic expression tree for the Example: arithmetic expression tree for the expression (2 expression (2 ((a a 1) 1) (3 (3 b))b))
2
a 1
3 b
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1212
Decision TreeDecision Tree
Binary tree associated with a decision processBinary tree associated with a decision process– internal nodes: questions with yes/no answerinternal nodes: questions with yes/no answer– external nodes: decisionsexternal nodes: decisions
Example: dining decisionExample: dining decision
Want a fast meal?
How about coffee? On expense account?
Starbucks Spike’s Al Forno Café Paragon
Yes No
Yes No Yes No
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1313
BinaryTree ADTBinaryTree ADTThe BinaryTree ADT The BinaryTree ADT extends the Tree extends the Tree ADT, i.e., it inherits ADT, i.e., it inherits all the methods of all the methods of the Tree ADTthe Tree ADT
Additional methods:Additional methods:– position position leftleft(p)(p)– position position rightright(p)(p)– boolean boolean hasLefthasLeft(p)(p)– boolean boolean hasRighthasRight(p)(p)
Update methods Update methods may be defined may be defined by data structures by data structures implementing the implementing the BinaryTree ADTBinaryTree ADT
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1414
Properties of Proper Binary TreesProperties of Proper Binary Trees
NotationNotationnn number of number of
nodesnodes
ee number of number of external nodesexternal nodes
ii number of number of internal nodesinternal nodes
hh heightheight
Properties:Properties:– e e i i 11
– n n 22e e 11– h h ii
– h h ((n n 1)1)22– e e 22hh
– h h loglog22 ee
– h h loglog22 ( (n n 1)1) 11
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1515
Inorder TraversalInorder TraversalIn an inorder traversal a In an inorder traversal a node is visited after its node is visited after its left subtree and before its left subtree and before its right subtreeright subtreeApplication: draw a binary Application: draw a binary treetree– x(v) = inorder rank of vx(v) = inorder rank of v– y(v) = depth of vy(v) = depth of v
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
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1616
Print Arithmetic ExpressionsPrint Arithmetic ExpressionsSpecialization of an Specialization of an inorder traversalinorder traversal– print operand or operator print operand or operator
when visiting nodewhen visiting node– print “(“ before traversing print “(“ before traversing
left subtreeleft subtree– print “)“ after traversing print “)“ after traversing
right subtreeright subtree
Algorithm printExpression(v)if hasLeft (v)
print(“(’’)inOrder (left(v))
print(v.element ())if hasRight (v)
inOrder (right(v))print (“)’’)
2
a 1
3 b((2 (a 1)) (3 b))
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1717
Evaluate Arithmetic Evaluate Arithmetic ExpressionsExpressions
Specialization of a Specialization of a postorder traversalpostorder traversal– recursive method recursive method
returning the value of a returning the value of a subtreesubtree
– when visiting an internal when visiting an internal node, combine the values node, combine the values of the subtreesof the subtrees
Algorithm evalExpr(v)if isExternal (v)
return v.element ()else
x evalExpr(leftChild (v))
y evalExpr(rightChild (v))
operator stored at vreturn x y
2
5 1
3 2
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1818
Euler Tour TraversalEuler Tour TraversalGeneric traversal of a binary treeGeneric traversal of a binary tree
Includes a special cases the preorder, postorder and inorder Includes a special cases the preorder, postorder and inorder traversalstraversals
Walk around the tree and visit each node three times:Walk around the tree and visit each node three times:– on the left (preorder)on the left (preorder)– from below (inorder)from below (inorder)– on the right (postorder)on the right (postorder)
2
5 1
3 2
LB
R
TreesTrees CSC311: Data StructuresCSC311: Data Structures 1919
Template Method PatternTemplate Method PatternGeneric algorithm that Generic algorithm that can be specialized by can be specialized by redefining certain stepsredefining certain stepsImplemented by means Implemented by means of an abstract Java class of an abstract Java class Visit methods that can be Visit methods that can be redefined by subclassesredefined by subclassesTemplate method Template method eulerToureulerTour– Recursively called on the Recursively called on the
left and right childrenleft and right children– A A ResultResult object with fields object with fields
leftResultleftResult,, rightResult rightResult andand finalResultfinalResult keeps track of keeps track of the output of the the output of the recursive calls to recursive calls to eulerToureulerTour
public abstract class EulerTour {protected BinaryTree tree;protected void visitExternal(Position p, Result r) { }protected void visitLeft(Position p, Result r) { }protected void visitBelow(Position p, Result r) { }
protected void visitRight(Position p, Result r) { } protected Object eulerTour(Position p) {
Result r = new Result();if tree.isExternal(p) { visitExternal(p, r); }
else {visitLeft(p, r);r.leftResult = eulerTour(tree.left(p));visitBelow(p, r);r.rightResult = eulerTour(tree.right(p));visitRight(p, r);return r.finalResult;
} …
TreesTrees CSC311: Data StructuresCSC311: Data Structures 2020
Specializations of EulerTourSpecializations of EulerTour
We show how to We show how to specialize class specialize class EulerTour to EulerTour to evaluate an evaluate an arithmetic arithmetic expressionexpression
AssumptionsAssumptions– External nodes External nodes
store Integer store Integer objectsobjects
– Internal nodes Internal nodes store store OperatorOperator objects objects supporting methodsupporting method
operation operation (Integer, Integer) (Integer, Integer)
public class EvaluateExpressionextends EulerTour {
protected void visitExternal(Position p, Result r) {r.finalResult = (Integer) p.element();
}
protected void visitRight(Position p, Result r) {Operator op = (Operator) p.element();r.finalResult = op.operation(
(Integer) r.leftResult,(Integer) r.rightResult);
}
…
}
TreesTrees CSC311: Data StructuresCSC311: Data Structures 2121
Linked Structure for TreesLinked Structure for TreesA node is represented by A node is represented by an object storingan object storing– ElementElement– Parent nodeParent node– Sequence of children Sequence of children
nodesnodes
Node objects implement Node objects implement the Position ADTthe Position ADT
B
DA
C E
F
B
A D F
C
E
TreesTrees CSC311: Data StructuresCSC311: Data Structures 2222
Linked Structure for Binary TreesLinked Structure for Binary TreesA node is represented A node is represented by an object storingby an object storing– ElementElement– Parent nodeParent node– Left child nodeLeft child node– Right child nodeRight child node
Node objects Node objects implement the Position implement the Position ADTADT
B
DA
C E
B
A D
C E
TreesTrees CSC311: Data StructuresCSC311: Data Structures 2323
Array-Based Representation Array-Based Representation of Binary Treesof Binary Trees
nodes are stored in an arraynodes are stored in an array
…
let rank(node) be defined as follows: rank(root) = 1 if node is the left child of parent(node),
rank(node) = 2*rank(parent(node)) if node is the right child of parent(node),
rank(node) = 2*rank(parent(node))+1
1
2 3
6 74 5
10 11
A
HG
FE
D
C
B
J
TreesTrees CSC311: Data StructuresCSC311: Data Structures 2424
Array-Based Representation of Array-Based Representation of Binary Trees: PropertiesBinary Trees: Properties
Let n be the number of nodes of a binary tree T Let pM be the maximum value of rank(v) over all the
nodes of T The array size N = pM+1
In the worst case, N = 2n