7/27/2019 Discrete Math- Tree
1/54
IEEM 2021 Discrete Mathematics 1
Chapter 9
Trees
IEEM 2021 Discrete Mathematics 2
7/27/2019 Discrete Math- Tree
2/54
IEEM 2021 Discrete Mathematics 3
9.1: Introduction to Trees9.1: Introduction to TreesDefinition 1Definition 1 (P.631): A(P.631): A treetree is ais a connectedconnected undirectedundirected
graph that contains no circuits.graph that contains no circuits.
Theorem 1 (P632):Theorem 1 (P632): There is a unique simple path between anyThere is a unique simple path between any
two of its nodes.two of its nodes.
A (notA (not--necessarilynecessarily--connected) undirected graph withoutconnected) undirected graph without
simple circuits is called asimple circuits is called a forestforest..You can think of it as a set of trees having disjoint sets ofYou can think of it as a set of trees having disjoint sets of
nodes.nodes.
AA leafleafnode in a tree or forest is any pendant or isolatednode in a tree or forest is any pendant or isolated
vertex. Anvertex. An internalinternalnode is any nonnode is any non--leaf vertex (thus itleaf vertex (thus it
has degreehas degree ___ ).___ ).
IEEM 2021 Discrete Mathematics 4
Tree and Forest ExamplesTree and Forest Examples
A Tree:A Tree: A Forest:A Forest:
Leaves in green, internal nodes in brown.
7/27/2019 Discrete Math- Tree
3/54
IEEM 2021 Discrete Mathematics 5
family tree
IEEM 2021 Discrete Mathematics 6
ExampleExample 1 (P. 632): Which graphs are trees?1 (P. 632): Which graphs are trees?
not connected
7/27/2019 Discrete Math- Tree
4/54
IEEM 2021 Discrete Mathematics 7
Rooted TreesRooted Trees
Definition 2Definition 2 (P.633): A(P.633): A rooted treerooted tree is a tree inis a tree in
which one node has been designated thewhich one node has been designated the rootroot.. Every edge is (implicitly or explicitly) directed awayEvery edge is (implicitly or explicitly) directed away
from the root.from the root.
You should know the following terms aboutYou should know the following terms about
rooted trees:rooted trees:
Parent, child, siblings, ancestors, descendents, leaf,Parent, child, siblings, ancestors, descendents, leaf,
internal node,internal node, subtreesubtree..
IEEM 2021 Discrete Mathematics 8
7/27/2019 Discrete Math- Tree
5/54
IEEM 2021 Discrete Mathematics 9
IEEM 2021 Discrete Mathematics 10
Rooted Tree ExamplesRooted Tree Examples
Note that a givenNote that a given unrootedunrooted tree withtree with nn nodesnodes
yieldsyields nn different rooted trees.different rooted trees.
root
root
Same tree
except
for choice
of root
7/27/2019 Discrete Math- Tree
6/54
IEEM 2021 Discrete Mathematics 11
RootedRooted--Tree Terminology ExerciseTree Terminology Exercise
Find theFind theparentparent,,childrenchildren,,siblingssiblings,,
ancestorsancestors, &, &
descendantsdescendants
of nodeof nodeff.. a
b
c
d
e
f
g
h
i
j k l
m
no
p
q
r
root
IEEM 2021 Discrete Mathematics 12
Example 2Example 2 (P. 634): Find(P. 634): Find
the parent ofthe parent ofcc..
the children ofthe children ofgg..
the siblings ofthe siblings ofhh..
all ancestors ofall ancestors ofee..all descendants ofall descendants ofbb..
all internal vertices.all internal vertices.
all leavesall leaves
subtreesubtree rooted atrooted at atatgg
7/27/2019 Discrete Math- Tree
7/54
IEEM 2021 Discrete Mathematics 13
Parent ofParent ofgg:: aa
Child ofChild ofgg:: hh,, ii,,jj
Siblings:Siblings: hh,, ii,,jj are sibling.are sibling.
Ancestors ofAncestors ofjj:: aa,,gg((aa has no ancestor.)has no ancestor.)
Descendents ofDescendents ofgg:: hh,, ii,,jj,, kk,, ll,, m.m.
Leaf:Leaf: dd,,ee,,ff,, kk,, ii,, ll,, mm..
Internal node:Internal node: VV{leaf vertices}{leaf vertices}
SubtreeSubtree with rootwith rootgg::
IEEM 2021 Discrete Mathematics 14
nn--aryary treestrees
Definition 3Definition 3 (P.634): A rooted tree is called(P.634): A rooted tree is called
nn--aryary if every vertex has no more thanif every vertex has no more than nn
children.children.
It is calledIt is calledfullfullif every internal (nonif every internal (non--leaf) vertexleaf) vertexhashas exactlyexactly nn children.children.
A 2A 2--ary tree is called aary tree is called a binary treebinary tree..
These are handy for describing sequences of yesThese are handy for describing sequences of yes--
no decisions.no decisions.
Example:Example: Comparisons in binary search algorithm.Comparisons in binary search algorithm.
7/27/2019 Discrete Math- Tree
8/54
IEEM 2021 Discrete Mathematics 15
Which Tree is Binary?Which Tree is Binary?
A given rooted tree is a binary treeA given rooted tree is a binary tree iffiffevery nodeevery node
other than the root has degreeother than the root has degree
___, and the root has___, and the root hasdegreedegree ___.___.
IEEM 2021 Discrete Mathematics 16
Example 3Example 3 (P. 634): Are the following rooted(P. 634): Are the following rooted
trees fulltrees full mm--aryary trees for some positive integertrees for some positive integermm..
full binary
tree
full 3-ary
tree
full 5-ary
tree
no
7/27/2019 Discrete Math- Tree
9/54
IEEM 2021 Discrete Mathematics 17
Ordered Rooted TreeOrdered Rooted Tree
This is just aThis is just a rooted treerooted tree in which thein which the
children of each internal node are ordered.children of each internal node are ordered.
In ordered binary trees, we can define:In ordered binary trees, we can define:
left child, right childleft child, right child
leftleft subtreesubtree, right, right subtreesubtree
ForFornn--aryary trees withtrees with nn > 2> 2, can use terms, can use terms
likelike leftmostleftmost,, rightmost,rightmost, etc.etc.
IEEM 2021 Discrete Mathematics 18
Example 4Example 4 (P. 635): Find(P. 635): Find
(1)(1) the left children ofthe left children ofdd..
(2)(2) the right children ofthe right children ofdd..
(3)(3) the leftthe left subtreesubtree ofofcc..
(4)(4) the rightthe right subtreesubtree ofofcc..SolutionSolution::
the left children ofthe left children ofdd::ff
the right children ofthe right children ofdd::gg
leftleft subtreesubtree ofofcc rightright subtreesubtree ofofcc
7/27/2019 Discrete Math- Tree
10/54
IEEM 2021 Discrete Mathematics 19
Trees as ModelsTrees as Models
Can use trees to model the following:Can use trees to model the following:
Saturated hydrocarbonsSaturated hydrocarbons
Organizational structuresOrganizational structures
Computer file systemsComputer file systems
In each case, would you use a rooted or aIn each case, would you use a rooted or a
nonnon--rooted tree?rooted tree?
IEEM 2021 Discrete Mathematics 20
Example 5Example 5 (P.636):(P.636): Saturated hydrocarbonsSaturated hydrocarbons
Arthur Cayley
1821 - 1895
There are exactly two different isomers of C4H10.
7/27/2019 Discrete Math- Tree
11/54
IEEM 2021 Discrete Mathematics 21
Example 6Example 6 (P.637):(P.637): Representing OrganizationRepresenting Organization
IEEM 2021 Discrete Mathematics 22
Example 6Example 6 (P.637):(P.637): Computer File SystemsComputer File Systems
7/27/2019 Discrete Math- Tree
12/54
IEEM 2021 Discrete Mathematics 23
Example 7Example 7 (P.638):(P.638): TreeTree--Connected Parallel ProcessorsConnected Parallel Processors
1st step:
P4: x1 +x2
P5: x3 +x4P6: x5 +x6
P7: x7 +x8
2nd step:
P2: (x1 +x2) + (x3 +x4)
P3: (x5 +x6) + (x7 +x8)
3rd step:
P1: [(x1+x2)+(x3+x4)]+[(x5+x6)+(x7+x8)]
IEEM 2021 Discrete Mathematics 24
Example 7Example 7 (P.638):(P.638): TreeTree--Connected Parallel ProcessorsConnected Parallel Processors
1st step:
P4: x1 +x2
2nd step:
P3: (x5 +x6) + (x7 +x8)
3rd step:
P1: [(x1+x2)+(x3+x4)]+[(x5+x6)+(x7+x8)]
2nd step:
P2: (x
1+x
2) + (x
3+x
4)
1st step:
P7: x7 +x81st step:
P6
: x5
+x6
1st step:
P5
: x3
+x4
7/27/2019 Discrete Math- Tree
13/54
IEEM 2021 Discrete Mathematics 25
Properties of TreesProperties of Trees
Theorem 2Theorem 2 (P. 638): Any tree with(P. 638): Any tree with nn nodes hasnodes has ee == nn 11edges.edges.
Proof:Proof: By Mathematical Induction.By Mathematical Induction.
Theorem 3Theorem 3 (P. 638):A full(P. 638):A full mm--aryary tree withtree with ii internalinternalnodes hasnodes has nn == mimi + 1+ 1 vertices, andvertices, and = (= (mm1)1)ii + 1+ 1 leaves.leaves.
Proof:Proof: There areThere are mimi children of internal nodes, plus the root.children of internal nodes, plus the root.
Thus,Thus, nn == mimi + 1+ 1. and,. and, == nn ii = (= (mm1)1)ii + 1+ 1..
Thus, whenThus, when mm is known and the tree is full, we canis known and the tree is full, we cancompute all four of the valuescompute all four of the values ee,, ii,, nn, and, and , given any, given any
one of them.one of them.
IEEM 2021 Discrete Mathematics 26
Theorem 4Theorem 4 (P. 639):(P. 639): A fullA full mm--aryary treetree
((ii)) nn verticesvertices
# of internal vertices# of internal vertices ii = (= (nn --1)/1)/m.m.
# of leaves# of leaves = [(= [(mm --1)1)nn + 1]/+ 1]/m.m.
((iiii)) ii internal verticesinternal vertices
# of vertices# of vertices nn == mimi +1.+1.
# of leaves# of leaves = (= (mm 1)1)ii + 1.+ 1.
((iiiiii)) leavesleaves
# of vertices# of vertices nn = (= (mm 1)/(1)/(mm 1).1).
# of internal vertices# of internal vertices ii = (= (ii --1)/(1)/(mm 1).1).
7/27/2019 Discrete Math- Tree
14/54
IEEM 2021 Discrete Mathematics 27
Some More Tree TheoremsSome More Tree Theorems
Definition:Definition: TheThe levellevelof a vertex is the length of theof a vertex is the length of the
simple path from the root to the node.simple path from the root to the node.
TheThe heightheightof a tree is maximum of theof a tree is maximum of the
levels of vertices.levels of vertices.
A rootedA rooted mm--aryary tree with heighttree with height hh isis
calledcalled balancedbalancedif all leaves are atif all leaves are at
levelslevels hh ororhh11..
Example 10Example 10 (P.640): What is the level of(P.640): What is the level of
each node? What is the height of this tree?each node? What is the height of this tree?
IEEM 2021 Discrete Mathematics 28
Example 11Example 11 (P.640)(P.640):: Which trees are balanced?Which trees are balanced?
Theorem 5Theorem 5(P.640)(P.640):: There are at mostThere are at most mmhh leaves in anleaves in an
mm--aryary tree of heighttree of height hh..
ProofProof:: mathematical inductionmathematical induction
7/27/2019 Discrete Math- Tree
15/54
IEEM 2021 Discrete Mathematics 29
Corollary 1Corollary 1 (P. 641)(P. 641):: AnAn mm--aryary tree withtree with
leaves has heightleaves has height hh loglogmm . If. Ifmm--aryary tree istree is
full and balanced thenfull and balanced then hh == loglogmm..
(i)(i)
(ii) If(ii) Ifmm--aryary tree is full,tree is full,
2
2
1 3 3
1 hm m m
+ +
+ + + +
# of leaves in a full m-ary tree
log .h ml m h l
log .h ml m h l = =
IEEM 2021 Discrete Mathematics 30
9.2: Applications of Trees9.2: Applications of Trees Binary search treesBinary search trees
A simple data structure for sorted listsA simple data structure for sorted lists
Decision treesDecision treesMinimum comparisons in sorting algorithmsMinimum comparisons in sorting algorithms
Prefix codesPrefix codes
Huffman codingHuffman coding
Game treesGame trees
7/27/2019 Discrete Math- Tree
16/54
IEEM 2021 Discrete Mathematics 31
Binary Search TreesBinary Search Trees
A representation for sorted sets of items.A representation for sorted sets of items.
Supports the following operations inSupports the following operations in (log(log nn))averageaverage--case time:case time:
Searching for an existing item.Searching for an existing item.
Inserting a new item, if not already present.Inserting a new item, if not already present.
Supports printing out all items inSupports printing out all items in ((nn) time.) time.
Note that inserting into a plain sequenceNote that inserting into a plain sequence aaiiwould instead takewould instead take ((nn) worst) worst--case time.case time.
IEEM 2021 Discrete Mathematics 32
Binary Search Tree FormatBinary Search Tree Format
Items are stored atItems are stored atindividual tree nodes.individual tree nodes.
We arrange for theWe arrange for thetree to always obeytree to always obeythis invariant:this invariant:
For every itemFor every itemxx,,
Every node inEvery node inxxss leftleftsubtreesubtree is less thanis less thanxx..
Every node inEvery node inxxss rightrightsubtreesubtree is greater thanis greater thanxx..
7
3 12
1 5 9 15
0 2 8 11
Example:
7/27/2019 Discrete Math- Tree
17/54
IEEM 2021 Discrete Mathematics 33
Example 1Example 1 (P. 644)(P. 644):: Form the binary search tree for theForm the binary search tree for the
words:words: mathematicsmathematics,,physicsphysics,,geographygeography,,zoologyzoology,,
meteorologymeteorology,,geologygeology,,psychologypsychology, and, and chemistrychemistry (using(using
alphabetical order).alphabetical order).
SolutionSolution::
not unique
May not be a balanced binary tree
IEEM 2021 Discrete Mathematics 34
Search on a binary tree:Search on a binary tree: If it present, we locate it.If it present, we locate it.
Otherwise, we try to add it to the binary search tree.Otherwise, we try to add it to the binary search tree.
In Algorithm 1, it locateIn Algorithm 1, it locatexx if it is already the key of aif it is already the key of a
vertex. Whenvertex. Whenxx is not a key, a new vertex with keyis not a key, a new vertex with keyxx isisadded to the tree. In theadded to the tree. In thepseudocodepseudocode,, vv is the vertexis the vertex
that hasthat hasxx as its key, andas its key, and label(label(vv) represents the key of) represents the key of
vertexvertex vv..
7/27/2019 Discrete Math- Tree
18/54
IEEM 2021 Discrete Mathematics 35
Recursive Binary Tree InsertRecursive Binary Tree Insert
IEEM 2021 Discrete Mathematics 36
Suppose we have a binary search treeSuppose we have a binary search tree TTfor a list offor a list ofnn
items. We may form a full binary treeitems. We may form a full binary tree UUfromfrom TTbyby
adding unlabeled vertices whenever necessary so thatadding unlabeled vertices whenever necessary so that
every vertex with a key has two children.every vertex with a key has two children.
7/27/2019 Discrete Math- Tree
19/54
IEEM 2021 Discrete Mathematics 37
Decision TreesDecision Trees
A decision tree represents aA decision tree represents a decisiondecision--makingmaking
processprocess.. Each possibleEach possible decision pointdecision point or situation isor situation is
represented by a node.represented by a node.
Each possible choice that could be made at thatEach possible choice that could be made at that
decision point is represented by an edge to a child node.decision point is represented by an edge to a child node.
In the extended decision trees used inIn the extended decision trees used in decisiondecision
analysisanalysis, we also include nodes that represent, we also include nodes that represent
random events and their outcomes.random events and their outcomes.
IEEM 2021 Discrete Mathematics 38
CoinCoin--Weighing ProblemWeighing Problem
Example 2Example 2 (P. 647): Suppose that(P. 647): Suppose that
you have 8 coins, one of which is ayou have 8 coins, one of which is a
lighter counterfeit, and a freelighter counterfeit, and a free--beambeam
balance.balance. (No scale of weight markings is(No scale of weight markings is
required for this problem!)required for this problem!)
How manyHow many weighingsweighings are needed toare needed to
guarantee that the counterfeit coinguarantee that the counterfeit coin
will be found?will be found?
?
7/27/2019 Discrete Math- Tree
20/54
IEEM 2021 Discrete Mathematics 39
A DecisionA Decision--Tree ProblemTree Problem
In each situation, we pick two disjoint and equalIn each situation, we pick two disjoint and equal--
size subsets of coins to put on the scale.size subsets of coins to put on the scale.
The balance then
decides whether
to tip left, tip right,
or stay balanced.
A given sequence of
weighings thus yields
a decision tree with
branching factor 3.
IEEM 2021 Discrete Mathematics 40
7/27/2019 Discrete Math- Tree
21/54
IEEM 2021 Discrete Mathematics 41
Applying the Tree Height TheoremApplying the Tree Height Theorem
The decision tree must have at least 8 leafThe decision tree must have at least 8 leaf
nodes, since there are 8 possible outcomes.nodes, since there are 8 possible outcomes.
In terms of which coin is the counterfeit one.In terms of which coin is the counterfeit one.
Recall the treeRecall the tree--height theorem,height theorem, hh loglogmm..
Thus the decision tree must have heightThus the decision tree must have height
hh loglog3388 == 1.8931.893 = 2= 2..
LetLet
s see if we solve the problem withs see if we solve the problem with
onlyonly
22 weighingsweighings
IEEM 2021 Discrete Mathematics 42
General Solution StrategyGeneral Solution Strategy
The problem is an example of searching for 1 unique particularThe problem is an example of searching for 1 unique particular
item, from among a list ofitem, from among a list ofnn otherwise identical items.otherwise identical items.
Somewhat analogous to the adage ofSomewhat analogous to the adage ofsearching for a needle in haystack.searching for a needle in haystack.
Armed with our balance, we can attack the problem using aArmed with our balance, we can attack the problem using adividedivide--andand--conquerconquer strategy, like whatstrategy, like whats done in binary search.s done in binary search.
We want to narrow down the set of possible locations where the dWe want to narrow down the set of possible locations where the desiredesired
item (coin) could be found down fromitem (coin) could be found down from nn to just 1, in a logarithmic fashion.to just 1, in a logarithmic fashion.
Each weighing has 3 possible outcomes.Each weighing has 3 possible outcomes.
Thus, we should use it to partition the search space into 3 piecThus, we should use it to partition the search space into 3 pieces that are ases that are as
close to equalclose to equal--sized as possible.sized as possible.
This strategy will lead to the minimum possible worstThis strategy will lead to the minimum possible worst--casecase
number ofnumber ofweighingsweighings required.required.
7/27/2019 Discrete Math- Tree
22/54
IEEM 2021 Discrete Mathematics 43
General Balance StrategyGeneral Balance Strategy
On each step, putOn each step, put nn/3/3 of theof the nn coins to becoins to be
searched on each side of the scale.searched on each side of the scale.
If the scale tips to the left, then:If the scale tips to the left, then:
The lightweight fake is in the right set ofThe lightweight fake is in the right set ofnn/3/3 nn/3/3 coins.coins.
If the scale tips to the right, then:If the scale tips to the right, then:
The lightweight fake is in the left set ofThe lightweight fake is in the left set ofnn/3/3 nn/3/3 coins.coins.
If the scale stays balanced, then:If the scale stays balanced, then:
The fake is in the remaining set ofThe fake is in the remaining set ofnn 22nn/3/3 nn/3/3 coins thatcoins thatwere not weighed!were not weighed!
Except ifExcept ifnn mod 3 = 1mod 3 = 1 then we can do a little betterthen we can do a little betterby weighingby weighing nn/3/3 of the coins on each side.of the coins on each side.
You can prove that this strategy always leads to a balanced 3-ary tree.
IEEM 2021 Discrete Mathematics 44
Coin Balancing Decision TreeCoin Balancing Decision Tree
How many weighing steps?How many weighing steps? TT((nn) =) = TT((nn/3) +/3) + CC
Here is what the tree looks like in our case:Here is what the tree looks like in our case:
123 vs 456
1 vs. 2
left:123 balanced:
78right:
456
7 vs. 84 vs. 5
L:1 R:2 B:3 L:4R:5 B:6 L:7 R:8
7/27/2019 Discrete Math- Tree
23/54
IEEM 2021 Discrete Mathematics 45
Example 3Example 3 (P.848): Give a decision tree that orders the(P.848): Give a decision tree that orders the
elements of the listelements of the list aa,, bb,, cc..
Theorem 1Theorem 1 (P.848): Any sorting algorithm based on(P.848): Any sorting algorithm based on
comparison requires at leastcomparison requires at least loglog22nn!! comparisons.comparisons.loglog22nn!! == ((nnloglog22nn))
IEEM 2021 Discrete Mathematics 46
Complexity of Sorting Algorithms Based on ComparisonsComplexity of Sorting Algorithms Based on Comparisons
Theorem 1Theorem 1 (P.848): Any sorting algorithm based on(P.848): Any sorting algorithm based on
comparison requires at leastcomparison requires at least log2log2nn!! comparisons.comparisons.
log2log2nn!! == ((nnloglog22nn))
Corollary 1Corollary 1 (P.848): The number of comparisons used by(P.848): The number of comparisons used by
a sorting algorithm to sort n elements based on binarya sorting algorithm to sort n elements based on binary
comparisons iscomparisons is ((nnloglog22nn).).
Theorem 2Theorem 2 (P.848): The average number of comparisons(P.848): The average number of comparisons
used by a sorting algorithm to sort n elements based onused by a sorting algorithm to sort n elements based on
binary comparisons isbinary comparisons is ((nnloglog22nn).).
7/27/2019 Discrete Math- Tree
24/54
IEEM 2021 Discrete Mathematics 47
(Grundy's Game): n ,
, ,
, ,
, n = 7, (
), ,
,( 7 )
( 5, 1, 1) ( 4, 2, 1 )
( 5, 2 ) ( 4, 3 )( 6, 1 )
( 3, 2, 2 ) ( 3, 3, 1 )
( 4, 1, 1, 1 )
( 3, 2, 1, 1 ) ( 2, 2, 2, 1 )
( 3, 1, 1, 1, 1 )
( 2, 1, 1, 1, 1, 1 )
( 2, 2, 1, 1, 1 )
( 7 )
( 5, 1, 1) ( 4, 2, 1 )
( 5, 2 ) ( 4, 3 )( 6, 1 )
( 3, 2, 2 ) ( 3, 3, 1 )
( 4, 1, 1, 1 )
( 3, 2, 1, 1 ) ( 2, 2, 2, 1 )
( 3, 1, 1, 1, 1 )
( 2, 1, 1, 1, 1, 1 )
( 2, 2, 1, 1, 1 )
n = 7
Game TreesGame Trees
IEEM 2021 Discrete Mathematics 48
(Nim Game) n , ,
, ,
n = 5, , ,
,5
level 12
3
1
1
level 2
3
2 1
4
12
2
1
00 level 3
1 1
1
1
0
1
level 4
123
2 1 1 0
001
level 5
1 2
3
1 2
0
1 1
1
1
1
1
level 0
7/27/2019 Discrete Math- Tree
25/54
IEEM 2021 Discrete Mathematics 49
5
level 12
3
1
1
level 2
3
2 1
4
12
2
1
00 level 3
1 1
1
1
0
1
level 4
123
2 1 1 0
001
level 5
1 2
3
1 2
0
1 1
1
1
1
1
level 0
IEEM 2021 Discrete Mathematics 50
Example 5 (P. 653)
Rule: (1) In each step, remove one or more stone from
exactly one of the piles. (2) A player without a legal
move loses.
7/27/2019 Discrete Math- Tree
26/54
IEEM 2021 Discrete Mathematics 51
Definition 1 (P. 654): The value of a vertex in a game
tree is defined recursively as follows:
(i) The value of a leaf is the payoff to the first palyer
when the game terminates in the position represented
by this leaf.(ii) The value of an internal vertex at an even level is the
maximum values of its children, and the value of an
internal vertex at the odd level is the minimum of
values of its children.
Theorem 3 (P. 654): The value of a vertex of a game
tree tells us the payoff to the first player if both players
follow minimax strategy and paly start from the positionrepresented by this vertex.
IEEM 2021 Discrete Mathematics 52
Example 7 (P. 655)
7/27/2019 Discrete Math- Tree
27/54
IEEM 2021 Discrete Mathematics 53
Example 6 (P. 653): Tic-tac-toe
IEEM 2021 Discrete Mathematics 54
7/27/2019 Discrete Math- Tree
28/54
IEEM 2021 Discrete Mathematics 55
IEEM 2021 Discrete Mathematics 56
7/27/2019 Discrete Math- Tree
29/54
IEEM 2021 Discrete Mathematics 57
IEEM 2021 Discrete Mathematics 58
9.3: Tree Traversal9.3: Tree TraversalProcedures for traversing all vertices of anProcedures for traversing all vertices of anordered rooted treeordered rooted tree
Universal address systemsUniversal address systems
Traversal algorithmsTraversal algorithmsDepthDepth--first traversal:first traversal:
Preorder traversalPreorder traversal
InorderInordertraversaltraversal
PostorderPostordertraversaltraversal
BreadthBreadth--first traversalfirst traversal
Infix/prefix/postfix notationInfix/prefix/postfix notation
7/27/2019 Discrete Math- Tree
30/54
IEEM 2021 Discrete Mathematics 59
Universal Address SystemsUniversal Address Systems
Example 1Example 1 (P. 660): Display the(P. 660): Display the labelingslabelings of theof the
universal address system. The lexicographic ordering ofuniversal address system. The lexicographic ordering of
thethe labelingslabelings isis
0 < 1.1 < 1.2 < 1.3 < 2 < 30 < 1.1 < 1.2 < 1.3 < 2 < 3
< 3.1< 3.1.1< 3.1.2< 3.1.2.1< 3.1< 3.1.1< 3.1.2< 3.1.2.1
< 3.1.2.2< 3.1.2.3
7/27/2019 Discrete Math- Tree
31/54
IEEM 2021 Discrete Mathematics 61
IEEM 2021 Discrete Mathematics 62
Example 2Example 2 (P. 662): List the order of elements by using(P. 662): List the order of elements by using
aapreorder traversalpreorder traversal..
a b e j k n o p f c d g l m h ia b e j k n o p f c d g l m h i
Priorities of
Preorder Traversal
Write, Left, Right
7/27/2019 Discrete Math- Tree
32/54
IEEM 2021 Discrete Mathematics 63
Example 3Example 3 (P. 662): List the order of elements by using(P. 662): List the order of elements by using
aapreorder traversalpreorder traversal..
IEEM 2021 Discrete Mathematics 64
InorderInorder TraversalTraversal
Definition 2Definition 2 (P. 662): Let(P. 662): Let TTbe a ordered rooted tree with rootbe a ordered rooted tree with root rr. If. If
TTconsists onlyconsists only rr, then, then rris theis the inorderinordertraversaltraversalofofTT. Otherwise,. Otherwise,
suppose thatsuppose that TT11,, TT22, . . . ,, . . . , TTnn are theare the subtreessubtrees atat rrfrom left to rightfrom left to right
inin TT. The. The inorderinordertraversaltraversalbegins by visitingbegins by visiting rr. It continues by. It continues by
traversingtraversing TT11
inin inorderinorder, then, then TT22
inin inorderinorder, and so on, until, and so on, until TTnn
isis
traversed intraversed in inorderinorder..
Priorities of Inorder
Traversal
Left, Write, Right
7/27/2019 Discrete Math- Tree
33/54
IEEM 2021 Discrete Mathematics 65
IEEM 2021 Discrete Mathematics 66
Example 4Example 4 (P. 664): List the order of elements by using(P. 664): List the order of elements by using
aa inorderinordertraversaltraversal..
7/27/2019 Discrete Math- Tree
34/54
IEEM 2021 Discrete Mathematics 67
PostorderPostorder TraversalTraversal
Definition 3Definition 3 (P. 664): Let(P. 664): Let TTbe a ordered rooted tree with rootbe a ordered rooted tree with root rr. If. If
TTconsists onlyconsists only rr, then, then rris theis thepostorderpostordertraversaltraversalofofTT. Otherwise,. Otherwise,
suppose thatsuppose that TT11
,, TT22
, . . . ,, . . . , TTnn
are theare the subtreessubtrees atat rrfrom left to rightfrom left to right
inin TT. The. Thepostorderpostordertraversaltraversalbegins by visitingbegins by visiting rr. It continues by. It continues by
traversingtraversing TT11 inin postorderpostorder, then, then TT22 inin postorderpostorder, and so on, until, and so on, until
TTnn is traversed inis traversed in postorderpostorder..
Priorities of Posorder
Traversal
Left, Right, Write
IEEM 2021 Discrete Mathematics 68
7/27/2019 Discrete Math- Tree
35/54
IEEM 2021 Discrete Mathematics 69
Example 3Example 3 (P. 662): List the order of elements by using(P. 662): List the order of elements by using
aapostorderpostordertraversaltraversal..
Priorities of Posorder
Traversal
Left, Right, Write
IEEM 2021 Discrete Mathematics 70
7/27/2019 Discrete Math- Tree
36/54
IEEM 2021 Discrete Mathematics 71
9.4: Spanning Trees9.4: Spanning Trees
Definition 1 (P. 675): Let Gbe a simple graph. A spanning
tree ofG is a subgraph ofG that is a tree containing everyvertex ofG.
not unique
IEEM 2021 Discrete Mathematics 72
Example 1Example 1 (P. 675): Find a spanning tree of the simple(P. 675): Find a spanning tree of the simple
graphgraph GG..
7/27/2019 Discrete Math- Tree
37/54
IEEM 2021 Discrete Mathematics 73
IEEM 2021 Discrete Mathematics 74
Theorem 1Theorem 1 (P. 676): A simple graph is connected if and(P. 676): A simple graph is connected if and
only if it has a spanning tree.only if it has a spanning tree.
Example 2Example 2 (P. 676):(P. 676): IP MulticastingIP Multicasting
7/27/2019 Discrete Math- Tree
38/54
IEEM 2021 Discrete Mathematics 75
Depth First SearchDepth First Search
Depth First SearchDepth First Search is also calledis also called backtrackingbacktracking, since, since
it returns to vertices previously visited to add path.it returns to vertices previously visited to add path.
"Never burn your bridges after crossing you may have to backtrack someday"
IEEM 2021 Discrete Mathematics 76
Example 3Example 3 (P. 678): Use a(P. 678): Use aDepth First SearchDepth First Search to findto find
spanning tree for the graphspanning tree for the graph GG..
7/27/2019 Discrete Math- Tree
39/54
IEEM 2021 Discrete Mathematics 77
Example 4Example 4 (P. 678): Use a(P. 678): Use aDepth First SearchDepth First Search to findto find
spanning tree for the graphspanning tree for the graph GG..
IEEM 2021 Discrete Mathematics 78
7/27/2019 Discrete Math- Tree
40/54
IEEM 2021 Discrete Mathematics 79
A maze
IEEM 2021 Discrete Mathematics 80
BreadthBreadth--First SearchFirst Search
7/27/2019 Discrete Math- Tree
41/54
IEEM 2021 Discrete Mathematics 81
Example 5Example 5 (P. 680): Use a(P. 680): Use aBreadth First SearchBreadth First Search to findto find
spanning tree for the graphspanning tree for the graph GG..
IEEM 2021 Discrete Mathematics 82
7/27/2019 Discrete Math- Tree
42/54
IEEM 2021 Discrete Mathematics 83
Exploring a town depth-first
not necessary be unique
Exploring a town using breadth-first search.
IEEM 2021 Discrete Mathematics 84
Backtracking ApplicationsBacktracking Applications
Example 6Example 6 (P. 682):(P. 682): Graph ColoringGraph Coloring Use backtrackingUse backtracking
(depth first search) to decide whether a graph(depth first search) to decide whether a graph GG can becan be
colored usingcolored using nn colors.colors.
7/27/2019 Discrete Math- Tree
43/54
IEEM 2021 Discrete Mathematics 85
Example 7Example 7 (P. 683):(P. 683): TheThe nn--Queens ProblemQueens Problem UseUse
backtracking (depth first search) to solve thebacktracking (depth first search) to solve the nn--queensqueens
problem.problem.
IEEM 2021 Discrete Mathematics 86
7/27/2019 Discrete Math- Tree
44/54
IEEM 2021 Discrete Mathematics 87
IEEM 2021 Discrete Mathematics 88
7/27/2019 Discrete Math- Tree
45/54
IEEM 2021 Discrete Mathematics 89
IEEM 2021 Discrete Mathematics 90
7/27/2019 Discrete Math- Tree
46/54
IEEM 2021 Discrete Mathematics 91
IEEM 2021 Discrete Mathematics 92
7/27/2019 Discrete Math- Tree
47/54
IEEM 2021 Discrete Mathematics 93
Depth First Search in Directed GraphDepth First Search in Directed Graph
Example 9Example 9 (P.684): Do the(P.684): Do the depth first searchdepth first search forfor
the following directed graph.the following directed graph.
Example 10Example 10 (P.685):(P.685): Web SpidersWeb Spiders
IEEM 2021 Discrete Mathematics 94
Example 10Example 10 (P.685):(P.685): Web SpidersWeb Spiders To indexTo index
websites, search engines such aswebsites, search engines such as googlegoogle, yahoo, yahoo
systematically explore the web starting at asystematically explore the web starting at a
known site. These search engines use programsknown site. These search engines use programs
called Web spiders (or crawlers or bots) to visitcalled Web spiders (or crawlers or bots) to visit
websites and analyze their contents. Webwebsites and analyze their contents. Web
spiders use both depthspiders use both depth--first searching andfirst searching and
breadthbreadth--first searching to create indices.first searching to create indices.
7/27/2019 Discrete Math- Tree
48/54
IEEM 2021 Discrete Mathematics 95
9.5: Minimum Spanning Trees9.5: Minimum Spanning TreesDefinition 1Definition 1 (P. 689): A(P. 689): A minimum spanning treeminimum spanning tree in ain a
connected weighted graph is a spanning tree that hasconnected weighted graph is a spanning tree that has
the smallest sum of weights of its edges.the smallest sum of weights of its edges.
Robert Clay Prim
1921-
It may not be unique.
IEEM 2021 Discrete Mathematics 96
7/27/2019 Discrete Math- Tree
49/54
IEEM 2021 Discrete Mathematics 97
Prims Algorithms ( 1957)
Prims Algorithm
O
A
C
B
E
DT
22
1
5
3 1
7 nodesMST has (7-1) edges.
19
IEEM 2021 Discrete Mathematics 98
O
O
A
2
Prims Algorithm
O
A
B
22
O
A
C
B
2 2
1
O
A
C
B
E
22
13
O
A
C
B
E
D
22
13
1
O
A
C
B
E
DT
22
1
5
31
20
7/27/2019 Discrete Math- Tree
50/54
IEEM 2021 Discrete Mathematics 99
Example 1Example 1 (P.690): Find the minimum spanning tree by(P.690): Find the minimum spanning tree by
usingusing PrimPrimss algorithm.algorithm.
IEEM 2021 Discrete Mathematics 100
Example 2Example 2 (P.690): Find the minimum spanning tree by(P.690): Find the minimum spanning tree by
usingusing PrimPrimss algorithm.algorithm.
7/27/2019 Discrete Math- Tree
51/54
IEEM 2021 Discrete Mathematics 101
IEEM 2021 Discrete Mathematics 102
Joseph BernardKruskal 1928-
7/27/2019 Discrete Math- Tree
52/54
IEEM 2021 Discrete Mathematics 103
5-edges
6-nodes
IEEM 2021 Discrete Mathematics 104
Kruskals Algorithm (1956)BC(1) DE(1) AB(2) AO(2) BE(3) BD(4) CE(4) CO(4) BO(5) DT(5) AD(7) ET(7)
O
A
C
B
E
DT
O
A
C
B
E
DT
1 1
O
A
C
B
E
DT
1
add BC add DE
7/27/2019 Discrete Math- Tree
53/54
7/27/2019 Discrete Math- Tree
54/54
IEEM 2021 Discrete Mathematics 107
Example 2Example 2 (P.692): Find the minimum spanning tree by(P.692): Find the minimum spanning tree by
usingusing KruskalKruskalss algorithm.algorithm.