Document 7522538
Download
Report
Transcript Document 7522538
ICS 241
• Discrete Mathematics II
– William Albritton, Information and Computer Sciences
Department at University of Hawai’i at Manoa
– For use with Kenneth H. Rosen’s Discrete Mathematics &
Its Applications (5th Edition)
– Based on slides originally created by
• Dr. Michael P. Frank, Department of Computer & Information
Science & Engineering at University of Florida
5/24/2016
1
Section 9.3: Tree Traversal
• Universal address systems
• Traversal algorithms
– Depth-first traversal:
• Preorder traversal
• Inorder traversal
• Postorder traversal
• Infix/prefix/postfix notation
5/24/2016
2
Universal Address Systems
• A way to label the nodes of an ordered rooted
tree
– Label the root with integer 0
– Label its children from left to right with 1, 2, 3, …
– For the next level down from vertex A, label its
children with A.1, A.2, A.3, …
5/24/2016
3
Class Exercise
• Exercise 3. (p. 672)
– Each pair of students should use only one sheet
of paper while solving the class exercises
5/24/2016
4
Traversal Algorithms
• Methods for visiting every node of an
ordered rooted tree
– Most common traversals:
• Preorder traversal
• Inorder traversal
• Postorder traversal
5/24/2016
5
Preorder Traversal
•
Steps:
Example:
1. Visit the root
2. Visit the leftmost
node in Preorder
3. Visit the 2nd leftmost
node in Preorder
4. Visit the Nth node …
•
Example traversal
– 7, 3, 1, 0, 2, 5, 12, 9,
8, 11, 15
5/24/2016
7
3
1
0
12
5
2
9
8
15
11
6
Inorder Traversal
•
Steps:
Example:
1. Visit the leftmost
node in Inorder
2. Visit the root
3. Visit the 2nd leftmost
node in Inorder
4. Visit the Nth node …
•
Example traversal
– 0, 1, 2, 3, 5, 7, 8, 9,
11, 12, 15
5/24/2016
7
3
1
0
12
5
2
9
8
15
11
7
Postorder Traversal
•
Steps:
Example:
1. Visit the leftmost
node in Postorder
2. Visit the 2nd leftmost
node in Postorder
3. Visit the Nth node …
4. Visit the root
•
Example traversal
– 0, 2, 1, 5, 3, 8, 11, 9,
15, 12, 7
5/24/2016
7
3
1
0
12
5
2
9
8
15
11
8
Class Exercise
• Exercise 7. (p. 673)
– Each pair of students should use only one sheet
of paper while solving the class exercises
5/24/2016
9
Infix/Prefix/Postfix Notation
• Can use an ordered, rooted tree to represent
arithmetic expressions
– Leaves represent variables or numbers
– Interior nodes represent operations
– Operations are evaluated from the bottom of the
tree to the top, and from the left node to the
right node
5/24/2016
10
Infix/Prefix/Postfix Notation
•
Infix
Example:
+
– ((1*6)-5)+((2↑5)/8)
•
Prefix
-
– +-*165/↑258
•
•
•
Polish notation
By Jan Lukasiewicz
*
/
↑
5
8
Infix
– 16*5-25↑8/+
•
5/24/2016
Reverse Polish
notation
1
6
2
5
11
Class Exercise
• Exercise 23. (p. 673)
– Each pair of students should use only one sheet
of paper while solving the class exercises
5/24/2016
12