Trees
Trees
• Applications:
– Organization charts
US International Laptops Desktops
– File systems
subtee
Exercise: Trees
• Answer the following questions about
A
the tree shown on the right:
– What is the size of the tree (number of
nodes)?
– Classify each node of the tree as a B C D
root, leaf, or internal node
– List the ancestors of nodes B, F, G, and
A. Which are the parents? E F G H
– List the descendents of nodes B, F, G,
and A. Which are the children?
– List the depths of nodes B, F, G, and A.
I J K
– What is the height of the tree?
– Draw the subtrees that are rooted at
node F and at node K.
Tree ADT
• We use positions to abstract • Query methods:
nodes • boolean isInternal(p)
• Generic methods: • boolean isLeaf (p)
• integer size() • boolean isRoot(p)
• boolean isEmpty() • Update methods:
• objectIterator elements() • swapElements(p, q)
• positionIterator positions() • object replaceElement(p, o)
• Accessor methods: • Additional update methods may
be defined by data structures
• position root()
implementing the Tree ADT
• position parent(p)
• positionIterator children(p)
A Linked Structure for General Trees
• A node is represented by an
object storing
• Element
• Parent node
B
• Sequence of children
nodes
• Node objects implement the
Position ADT
A D F
D
A F
C E
C E
A Linked Structure for General Trees
• A node is represented by an
object storing
• Element
• Parent node
B
• Sequence of children
nodes
• Node objects implement the
Position ADT
A D F
D
A F
C E
C E
A Linked Structure for General Trees
• A node is represented by an
object storing
• Element
• Parent node
B
• Sequence of children
nodes
• Node objects implement the
Position ADT
A D F
D
A F
C E
C E
A Linked Structure for General Trees
• A node is represented by an
object storing
• Element
• Parent node
B
• Sequence of children
nodes
• Node objects implement the
Position ADT
A D F
D
A F
C E
C E
Preorder Traversal
• A traversal visits the nodes of a tree Algorithm preOrder(v)
in a systematic manner visit(v)
• In a preorder traversal, a node is for each child w of v
visited before its descendants preOrder(w)
• Application: print a structured
document
1
Data Structures & Algorithms
2 5 9
3 6
4 7 8
1.1 Basic C++ 2.1 Goals, Principles, 2.2 Inheritance and
1.2 Expressions 2.3 Templates
Programming Elements and Patterns Polymorphism
Exercise: Preorder Traversal
• In a preorder traversal, a node is
A
visited before its descendants
• List the nodes of this tree in
preorder traversal order.
B C D
E F G H
Algorithm preOrder(v)
visit(v)
for each child w of v I J K
preOrder (w)
Postorder Traversal
• In a postorder traversal, a node is Algorithm postOrder(v)
visited after its descendants for each child w of v
• Application: compute space used postOrder(w)
by files in a directory and its visit(v)
subdirectories
9
cs16/
8
3 7
todo.txt
homeworks/ programs/
1K
1 2 4 5 6
h1c.doc h1nc.doc DDR.java Stocks.java Robot.java
3K 2K 10K 25K 20K
Exercise: Postorder Traversal
• In a postorder traversal, a node is A
visited after its descendants
• List the nodes of this tree in postorder
traversal order. B C D
E F G H
Algorithm postOrder(v)
for each child w of v
I J K
postOrder(w)
visit(v)
Binary Tree
• A binary tree is a tree with the • Applications:
following properties: • arithmetic expressions
• Each internal node has two children • decision processes
• The children of a node are an ordered • searching
pair
• We call the children of an internal A
node left child and right child
• Alternative recursive definition: a
binary tree is either B C
• a tree consisting of a single node, or
• a tree whose root has an ordered pair
of children, each of which is a binary D E F G
tree
H I
Arithmetic Expression Tree
• Binary tree associated with an arithmetic expression
• internal nodes: operators
• leaves: operands
• Example: arithmetic expression tree for the expression
(2 (a 1) (3 b))
2 3 b
a 1
Decision Tree
• Binary tree associated with a decision process
• internal nodes: questions with yes/no answer
• leaves: decisions
• Example: dining decision
Want a fast meal?
Yes No
Yes No Yes No
• n 2l 1
l number of leaves • h i
i number of internal • h (n 1)2
nodes • l 2h
h height • h log2 l
• h log2 (n 1) 1
Properties of Binary Trees
• Full (or proper) binary tree
• All nodes have either 0 or 2 children
Properties of Binary Trees
• Complete binary tree with height h
• All 2h-1 nodes exist at height h-1
• Nodes at level h fill up left to right
BinaryTree ADT
B A D
A D
C E C E
Inorder Traversal
• In an inorder traversal a node Algorithm inOrder(v)
is visited after its left subtree if isInternal(v)
and before its right subtree inOrder(leftChild(v))
• Application: draw a binary tree visit(v)
• x(v) = inorder rank of v if isInternal(v)
• y(v) = depth of v inOrder(rightChild(v))
2 8
1 4 7 9
3 5
Exercise: Inorder Traversal
• In an inorder traversal a node is
A
visited after its left subtree and
before its right subtree
• List the nodes of this tree in inorder
B C
traversal order.
E F G H
Algorithm inOrder(v)
if isInternal(v)
inOrder(leftChild(v)) I K
visit(v)
if isInternal(v)
inOrder(rightChild(v))
Exercise: Preorder & InOrder Traversal
2 3 b
((2 (a 1)) (3 b))
a 1
Evaluate Arithmetic Expressions
• Specialization of a postorder Algorithm evalExpr(v)
traversal if isLeaf(v)
• recursive method returning return v.element()
the value of a subtree else
• when visiting an internal x
evalExpr(leftChild(v))
node, combine the values of
the subtrees y
evalExpr(rightChild(v))
operator stored at v
return x y
2 3 b
a 1
Exercise: Arithmetic Expressions
8 8 2 4
Exercise: Arithmetic Expressions
L R
B
2 3 2
5 1
Euler Tour Traversal
Algorithm eulerTour(p)
left-visit-action(p)
if isInternal(p)
eulerTour(p.left())
bottom-visit-action(p)
if isInternal(p)
eulerTour(p.right())
right-visit-action(p)
End Algorithm
L R
B
2 3 2
5 1
Print Arithmetic Expressions
• Specialization of an Euler Tour Algorithm printExpression(p)
traversal if isExternal(p) then
• Left-visit-action: if node is print value stored at p
internal, print “(“ Else
• Bottom-visit-action: print value print “(“
or operator stored at node
• Right-visit-action: if node is
printExpression(p.left())
internal, print “)” Print the operator stored
at p
printExpression(p.right())
print “)”
Endif
End Algorithm
2 3 b
((2 (a 1)) (3 b))
a 1
Template Method Pattern
class EulerTour {
• Generic algorithm that can protected:
be specialized by redefining BinaryTree* tree;
virtual void visitLeaf(Position p, Result
certain steps r) { }
• Implemented by means of virtual void visitLeft(Position p, Result
r) { }
an abstract C++ class virtual void visitBelow(Position p, Result
• Visit methods that can be r) { }
redefined by subclasses virtual void visitRight(Position p, Result
r) { }
• Template method eulerTour int eulerTour(Position p) {
• Recursively called on the Result r = initResult();
if (tree–>isLeaf(p)) {
left and right children visitLeaf(p, r);
• A Result object with fields return r.finalResult;
leftResult, rightResult and } else {
finalResult keeps track of visitLeft(p, r);
r.leftResult = eulerTour(tree–
the output of the recursive >leftChild(p));
calls to eulerTour visitBelow(p, r);
r.rightResult = eulerTour(tree–
>rightChild(p));
visitRight(p, r);
return r.finalResult;
Specializations of EulerTour
class EvaluateExpression : public EulerTour
• We show how to specialize {
class EulerTour to evaluate protected:
an arithmetic expression void visitLeaf(Position p, Result r) {
r.finalResult = p.element().value();
• Assumptions }
• External nodes support a void visitRight(Position p, Result r) {
Operator op = p.element().operator();
function value(), which r.finalResult = op.operation(
returns the value of this r.leftResult,
node. r.rightResult);
}
• Internal nodes provide a
function operation(int, // … other details omitted
};
int), which returns the
result of some binary
operator on integers.