Travesal Methods
Travesal Methods
Travesal Methods
• Preorder
• Inorder
• Postorder
• Level order
Preorder Traversal
public static void preOrder(BinaryTreeNode t)
{
if (t != null)
{
visit(t);
preOrder(t.leftChild);
preOrder(t.rightChild);
}
}
b c
abc
Preorder Example (visit = print)
a
b c
f
d e
g h i j
abdghei cf j
* +
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
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
Postorder Traversal
public static void postOrder(BinaryTreeNode t)
{
if (t != null)
{
postOrder(t.leftChild);
postOrder(t.rightChild);
visit(t);
}
}
Postorder Example (visit = print)
a
b c
bca
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 + /
Traversal Applications
a
b c
f
d e
g h i j
• Make a clone.
• Determine height.
•Determine number of nodes.
Level Order
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
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