Title: Tree Traversal
1Tree Traversal
2Traversal Algorithms
- A traversal algorithm is a procedure for
systematically visiting every vertex of an
ordered rooted tree - An ordered rooted tree is a rooted tree where the
children of each internal vertex are ordered - Three common traversals are
- Preorder traversal
- Inorder traversal
- Postorder traversal
3Traversal
- 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.
4Preorder Traversal
Step 1 Visit r
Step 2 Visit T1 in preorder
Step 3 Visit T2 in preorder
Step n1 Visit Tn in preorder
5Example
A
R
E
Y
P
M
H
J
Q
T
6Inorder Traversal
Step 1 Visit T1 in inorder
Step 2 Visit r
Step 3 Visit T2 in inorder
Step n1 Visit Tn in inorder
7Example
A
R
E
Y
P
M
H
J
Q
T
8Postorder Traversal
Step 1 Visit T1 in postorder
Step 2 Visit T2 in postorder
Step n Visit Tn in postorder
Step n1 Visit r
9Example
A
R
E
Y
P
M
H
J
Q
T
10Representing Arithmetic Expressions
- Complicated arithmetic expressions can be
represented by an ordered rooted tree - Internal vertices represent operators
- Leaves represent operands
- Build the tree bottom-up
- Construct smaller subtrees
- Incorporate the smaller subtrees as part of
larger subtrees
11Example
12Infix Notation
- Traverse in inorder adding parentheses for each
operation
x
y
2
x
3
y
2
?
/
13Prefix Notation(Polish Notation)
x
y
2
x
3
y
2
?
/
14Evaluating Prefix Notation
- In an prefix expression, a binary operator
precedes its two operands - The expression is evaluated right-left
- Look for the first operator from the right
- Evaluate the operator with the two operands
immediately to its right
15Example
/ 2 2 2 / 3 2 1 0
/ 2 2 2 / 3 2 1
/ 2 2 2 / 1 1
/ 2 2 2 1
/ 4 2 1
2 1
3
16Postfix Notation(Reverse Polish)
x
y
2
x
3
y
2
?
/
17Evaluating Postfix Notation
- In an postfix expression, a binary operator
follows its two operands - The expression is evaluated left-right
- Look for the first operator from the left
- Evaluate the operator with the two operands
immediately to its left
18Example
2 2 2 / 3 2 1 0 /
4 2 / 3 2 1 0 /
2 3 2 1 0 /
2 1 1 0 /
2 1 1 /
2 1
3
19Exercises
- 7, 9, 10, 12, 13, 15, 16, 17, 18, 23, 24