Professional Documents
Culture Documents
Section 9.3
Longin Jan Latecki
Temple University
Based on slides by
Paul Tymann, Andrew Watkins,
and J. van Helden
1
Tree Anatomy
The children of a node are, themselves, trees, called subtrees.
Level 0
Level 1
Level 2
Level 3
Root
T
U
Internal Node
Leaf
Z
Child of X
Parent of Z and Y
Subtree
Tree Traversals
One of the most common operations
performed on trees, are a tree traversals
A traversal starts at the root of the tree and
visits every node in the tree exactly once
visit means to process the data in the node
7
6
10
4
3
13
7, 6, 10, 4, 8, 13, 3, 5
Step Output
Queue
Depth-First Traversals
There are 8 different depth-first traversals
7
6
10
4
3
13
7, 6, 4, 3, 5, 10, 8, 13
Step Output
Stack
Preorder Traversal
Step 1: Visit
r
Step 2: Visit T1 in
preorder
Step 3: Visit T in
preorder
T1
T2
Tn
Example
M
A
H
P
E
11
R
2.1
1.1
3
H
2.2
E
12
7
6
10
4
3
13
3, 4, 5, 6, 7, 8, 10, 13
13
Inorder Traversal
Step 1: Visit T1 in
inorder
Step 2: Visit r
Step 3: Visit T2 in
inorder
T1
T2
Tn
Example
M
A
H
P
E
15
inorder (t)
if t != NIL: {
inorder (left[t]);
write (label[t]);
inorder (right[t]); }
7
6
10
4
3
13
3, 5, 4, 6, 8, 13, 10, 7
17
Postorder Traversal
Step 1: Visit T1 in
postorder
Step 2: Visit T2 in
postorder
Step n: Visit Tn in
postorder
Step
n+1: Visit r
T1
T2
Tn
18
Example
M
A
H
P
M
19
Representing Arithmetic
Expressions
Complicated arithmetic expressions can be
represented by an ordered rooted tree
Internal vertices represent operators
Leaves represent operands
Example
(x+y)2 + (x-3)/(y+2)
+
+
x y
x 3 y 2
21
Infix Notation
Traverse in inorder (LVR) adding parentheses for each
operation
+
x y
x 3 y 2
Prefix Notation
(Polish Notation)
Traverse in preorder (VLR)
+
x y
x 3 y 2
+ +x y 2 / x3+y2
23
Example
+
1
+
2
+
1
+
1
+
/ + 2 2 2 / 3 2 +
0
/ + 2 2 2 / 3
1
/ + 2 2 2 / 1
/ + 2 2 2
/ 4 2 1
+ 2 1
3
25
Postfix Notation
(Reverse Polish)
Traverse in postorder (LRV)
+
x y
x 3 y 2
x y +2 x 3 y 2 + / +
26
27
Example
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
28