Java Reference
In-Depth Information
// then print right subtree in a preorder manner
}
}
This is a time to make the leap of faith that is so essential in writing recursive
methods. Thinking recursively, you'll think, “If only I had a method to print a subtree
in a preorder manner . . . but I do have such a method . . . the one I'm writing.”
Therefore, this method becomes:
private void printPreorder(IntTreeNode root) {
if (root != null) {
System.out.print(" " + root.data);
printPreorder(root.left);
printPreorder(root.right);
}
}
That modification completes the method. It may seem odd that it takes so little
code to perform this task, but as we saw in Chapter 12, recursive code often ends up
being very short.
Now let's consider how to modify the code to print the tree in an inorder manner.
The new code will have a similar public/private pair of methods:
public void printInorder() {
System.out.print("inorder:");
printInorder(overallRoot);
System.out.println();
}
private void printInorder(IntTreeNode root) {
...
}
The code will also have a similar test for an empty tree. But how do you change
the body of the private printing method to make it print using an inorder traversal
rather than a preorder traversal? You put the print in between the two recursive
calls:
private void printInorder(IntTreeNode root) {
if (root != null) {
printInorder(root.left);
System.out.print(" " + root.data);
printInorder(root.right);
}
}
Search WWH ::




Custom Search