- pre-order traversal - The word "pre-order" refers to when the root is processed; it is processed previous to its two subtrees. So a pre-order traversal has these three steps for a non-empty tree:
- Process the root.
- Process the nodes in the left subtree with a recursive call.
- Process the nodes in the right subtree with a recursive call.
public void preorderPrint( ) {
System.out.println(data);
if (left != null)
left.preorderPrint( );
if (right != null)
right.preorderPrint( );
}
Example:
Output:
14
17
9
13
53
11
- in-order traversal - For "in-order" traversal the main difference iis that the root is processed in between the processing of its two subtrees. Here are the three
steps for a non-empty tree:
- Process the nodes in the left subtree with a recursive call.
- Process the root.
- Process the nodes in the right subtree with a recursive call.
public void inorderPrint( ) {
if (left != null
left.inorderPrint( );
System.out.println(data);
if (right != null)
right.inorderPrint( );
}
Example:
Output:
9
13
17
53
14
11
- post-order traversal - In "post-order" traversal the processing of the root is postponed until last in a non-empty tree (think of it as bottom up, left to right):
- Process the nodes in the left subtree with a recursive call.
- Process the nodes in the right subtree with a recursive call.
- Process the root.
public void postorderPrint( ) {
if (left != null
left.postorderPrint( );
if (right != null)
right.postorderPrint( );
System.out.println(data);
}
Example:
Output:
13
9
53
17
11
14