Lecture 13 Tree
Lecture 13 Tree
• Pre-order traversal
• Visit node, traverse left subtree, traverse right subtree
• Node-left-right
• In-order traversal
• Traverse left subtree, visit node, traverse right subtree
• Left-node-right
• Post-order traversal
• Traverse left subtree, traverse right subtree, visit node
• Left-right-node
Example
Tree: M
A Y E
J R H
P Q T
Visiting sequence:
M A J Y R H P Q T E
The Preorder Traversal of T
In which order
does a preorder
traversal visit
the vertices in
the ordered
rooted tree T
shown to the
left?
Preorder:
Visit root, then
visit subtrees
left to right.
The Preorder Traversal of T
© The
McGraw-Hill
Companies,
Inc. all rights
reserved
Preorder:
Visit root, then
visit subtrees
left to right.
The Preorder Traversal of T
© The McGraw-Hill Companies, Inc. all rights reserved
The Preorder Traversal of T
© The McGraw-Hill Companies, Inc. all rights reserved
The Preorder Traversal of T
© The McGraw-Hill Companies, Inc. all rights reserved
Example
Tree: M
A Y E
J R H
P Q T
Visiting sequence:
J A M R Y P H Q T E
The 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.
The Inorder Traversal of T
© The McGraw-Hill
Companies, Inc. all rights
reserved
Inorder:
Visit
leftmost tree,
visit root,
visit other
subtrees left
to right.
The Inorder Traversal of T
Tree: M
A Y E
J R H
P Q T
Visiting sequence:
J A R P Q T H Y E M
The Postorder Traversal of T
In which order
does a postorder
traversal visit
the vertices in
the ordered
rooted tree T
shown to the
left?
Postorder:
Visit subtrees
left to right, then
visit root.
The Postorder Traversal of T
© The
McGraw-Hill
Companies,
Inc. all rights
reserved
Postorder:
Visit
subtrees left
to right,
then visit
root.
The Postorder Traversal of T
© The McGraw-Hill Companies, Inc. all rights reserved
The Postorder Traversal of T
© The McGraw-Hill Companies, Inc. all rights reserved
The Postorder Traversal of T
(x+y)2 + (x-3)/(y+2)
+
/
+ 2 – +
x y x 3 y 2
Infix Notation
+ 2 – +
x y x 3 y 2
(((x + y) 2)+((x – 3) / (y + 2)))
Prefix Notation (Polish Notation)
• Traverse in preorder:
+
/
+ 2 – +
x y x 3 y 2
+ +x y 2 / – x3+y2
Evaluating Prefix Notation
+ / + 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
Postfix Notation (Reverse Polish)
• Traverse in postorder
+
/
+ 2 – +
x y x 3 y 2
x y +2 x 3 – y 2 + / +
Evaluating Postfix Notation
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
Any Questions?