0% found this document useful (0 votes)
19 views35 pages

Trees

binary tree binary search tree

Uploaded by

dollychaaban
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views35 pages

Trees

binary tree binary search tree

Uploaded by

dollychaaban
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

Trees

Outline and Reading


• Tree Definitions and ADT (§7.1)
• Tree Traversal Algorithms for General Trees
(preorder and postorder) (§7.2)
• BinaryTrees (§7.3)
• Data structures for trees (§7.1.4 and §7.3.4)
• Traversals of Binary Trees (preorder, inorder,
postorder) (§7.3.6)
• Euler Tours (§7.3.7)
What is a Tree
• In Computer Science, a
tree is an abstract model Computers”R”Us
of a hierarchical structure
• A tree consists of nodes
with a parent-child relation Sales Manufacturing R&D

• Applications:
– Organization charts
US International Laptops Desktops
– File systems

Europe Asia Canada


Tree Terminology
• Root: node without parent (A) • Subtree: tree consisting of a
• Internal node: node with at least one node and its descendants
child (A, B, C, F)
• Leaf (aka External node): node without A
children (E, I, J, K, G, H, D)
• Ancestors of a node: parent,
grandparent, great-grandparent, etc. B C D
• Depth of a node: number of ancestors
• Height of a tree: maximum depth of
any node (3) E F G H
• Descendant of a node: child,
grandchild, great-grandchild, etc.
I J K

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

1. A C++ Primer 2. Object-Oriented Design Bibliography

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

How about coffee? On expense account?

Yes No Yes No

Starbucks Antonio’s Veritas Chili’s


Properties of Binary Trees
• Notation • Properties:
li1
n number of nodes

• 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

• The BinaryTree ADT • Update methods may


extends the Tree ADT, be defined by data
i.e., it inherits all the structures
methods of the Tree implementing the
ADT BinaryTree ADT
• Additional methods:
• position leftChild(p)
• position rightChild(p)
• position sibling(p)
A Linked Structure for Binary
Trees
• A node is represented by
an object storing 
• Element
• Parent node
• Left child node B
• Right child node
• Node objects implement  
the Position 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

• Draw a (single) binary tree T, such that


• Each internal node of T stores a single
character
• A preorder traversal of T yields EXAMFUN
• An inorder traversal of T yields MAFXUEN
Print Arithmetic Expressions
• Specialization of an inorder Algorithm printExpression(v)
traversal if isInternal(v)
• print operand or operator when print(“(’’)
visiting node printExpression(leftChild(v))
• print “(“ before traversing left print(v.element())
subtree
• print “)“ after traversing right if isInternal(v)
subtree printExpression(rightChild(v))
print (“)’’)

 

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

• Draw an expression tree that has


• Four leaves, storing the values 2, 4, 8, and 8
• 3 internal nodes, storing operations +, -, *, / (operators
can be used more than once, but each internal node
stores only one)
• The value of the root is 24
Exercise: Arithmetic Expressions

• Draw an expression tree that has


• Four leaves, storing the values 2, 4, 8, and 8
• 3 internal nodes, storing operations +, -, *, / (operators
can be used more than once, but each internal node
stores only one)
• The value of the root is 24

 

8 8 2 4
Exercise: Arithmetic Expressions

• Draw an expression tree that has


• Four leaves, storing the values 1, 3, 4, and 8
• 3 internal nodes, storing operations +, -, *, / (operators
can be used more than once, but each internal node
stores only one)
• The value of the root is 24
Euler Tour Traversal
• Generic traversal of a binary tree
• Includes as special cases the preorder, postorder and inorder traversals
• Walk around the tree and visit each node three times:
• on the left (preorder)
• from below (inorder)
• on the right (postorder)

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.

You might also like