Traversal Methods
Traversal Methods
• Preorder
• Inorder
• Postorder
• Level order
Preorder Traversal
void preOrder(treePointer ptr)
{
if (ptr != NULL)
{
visit(t);
preOrder(ptr->leftChild);
preOrder(ptr->rightChild);
}
}
Preorder Example (Visit = print)
a
b c
abc
Preorder Example (Visit = print)
a
b c
f
d e
g h i j
abdghei cf j
Preorder Of Expression Tree
/
* +
e f
+ -
a b c d
/ * +a b - c d +e f
b c
bac
Inorder Example (Visit = print)
a
b c
f
d e
g h i j
gdhbei af j c
Inorder By Projection (Squishing)
a
b c
f
d e
g h i j
g d h b e i a f jc
Inorder Of Expression Tree
/
* +
e f
+ -
a b c d
a + b * c - d/ e + f
4 5
Morris Traversal
No stacks, no recursion!
Inorder Traversal
P
M L
S E
R
A A
T E
E
inorder predecessor of node with left subtree
is the right child of node’s left subtree
Morris Traversal
b c
bca
Postorder Example (Visit = print)
a
b c
f
d e
g h i j
ghdi ebj f ca
Postorder Of Expression Tree
/
* +
e f
+ -
a b c d
a b +c d - * e f + /
b c
f
d e
g h i j
• Make a clone.
• Determine height.
• Determine number of nodes.
Level Order
Let ptr be a pointer to the tree root.
while (ptr != NULL)
{
visit node pointed at by ptr and put its children on
a FIFO queue;
if FIFO queue is empty, set ptr = NULL;
otherwise, delete a node from the FIFO queue and
call it ptr;
}
Level-Order Example (Visit = print)
a
b c
f
d e
g h i j
abcdef ghi j
Binary Tree Construction
• Suppose that the elements in a binary tree
are distinct.
• Can you construct the binary tree from
which a given traversal sequence came?
• When a traversal sequence has more than
one element, the binary tree is not uniquely
defined.
• Therefore, the tree from which the sequence
was obtained cannot be reconstructed
uniquely.
Some Examples
preorder a a
= ab b b
inorder b a
= ab a b
postorder b b
= ab a a
level order a a
= ab b b
Binary Tree Construction
preorder = ab a a
postorder = ba b b
gdhbei fjc
Inorder And Preorder
a
gdhbei fjc
• preorder = a b d g h e i c f j
• b is the next root; gdh are in the left
subtree; ei are in the right subtree.
a
b fjc
gdh ei
Inorder And Preorder
a
b fjc
gdh ei
• preorder = a b d g h e i c f j
• d is the next root; g is in the left
subtree; h is in the right subtree.
a
b fjc
d ei
g h
Inorder And Postorder