Presentation on theme: "Chapter 10, Section 10.3 Tree Traversal"— Presentation transcript:
1Chapter 10, Section 10.3 Tree Traversal These class notes are based on material from our textbook, Discrete Mathematics and Its Applications, 6th ed., by Kenneth H. Rosen, published by McGraw Hill, Boston, MA, They are intended for classroom use only and are not a substitute for reading the textbook.
2Universal Address Systems To totally order the vertices of on orered rooted tree:Label the root with the integer 0.Label its k children (at level 1) from left to right with 1, 2, 3, …, k.For each vertex v at level n with label A, label its kv children, from left to right, with A.1, A.2, A.3, …, A.kv.This labeling is called the universal address system of the ordered rooted tree.
4Traversal AlgorithmsA traversal algorithm is a procedure for systematically visiting every vertex of an ordered rooted treeAn ordered rooted tree is a rooted tree where the children of each internal vertex are orderedThe three common traversals are:Preorder traversalInorder traversalPostorder traversal
5Traversal Let T be an ordered rooted tree with root r. Suppose T1, T2, …,Tn are the subtrees at r from left to right in T.rT1T2Tn
6Preorder Traversal Step 1: Visit r Step 2: Visit T1 in preorder .Step n+1: Visit Tn in preorderrT1T2Tn
14Inorder Traversal Step 1: Visit T1 in inorder Step 2: Visit r .Step n+1: Visit Tn in inorderrT1T2Tn
15Example Tree: Visiting sequence: A R E Y P M H J Q T J A M R Y P H Q T
16The Inorder Traversal of T In which order does an inorder traversal visit the vertices in the ordered rooted tree T shown to the left?Inorder:Visit leftmost tree, visit root, visit other subtrees left to right.
28Representing Arithmetic Expressions Complicated arithmetic expressions can be represented by an ordered rooted treeInternal vertices represent operatorsLeaves represent operandsBuild the tree bottom-upConstruct smaller subtreesIncorporate the smaller subtrees as part of larger subtrees
30Infix NotationTraverse in inorder adding parentheses for each operation+–/2xy3()()()x+y2+()()x–3/()y+2
31Prefix Notation (Polish Notation) Traverse in preorder:+–/2xy3++xy2/–x3+y2
32Evaluating Prefix Notation In an prefix expression, a binary operator precedes its two operandsThe expression is evaluated right-leftLook for the first operator from the rightEvaluate the operator with the two operands immediately to its right
34Postfix Notation (Reverse Polish) Traverse in postorder+–/2xy3xy+2x3–y2+/+
35Evaluating Postfix Notation In an postfix expression, a binary operator follows its two operandsThe expression is evaluated left-rightLook for the first operator from the leftEvaluate the operator with the two operands immediately to its left