Java Reference
In-Depth Information
printPreorder(overallRoot);
System.out.println();
}
How do you write the private method? It's good to go back to the basic definition
of a binary tree. Remember that it is either an empty tree or a root node with left and
right subtrees. If it's an empty tree, then there isn't anything to print. That means you
could begin your private method this way:
private void printPreorder(IntTreeNode root) {
if (root == null) {
// do nothing
}
...
}
But since this case leaves the method with nothing to do, it's better to test the
negation of this statement:
private void printPreorder(IntTreeNode root) {
if (root != null) {
...
}
}
And what do you do if node is not null ? In that case, you have a root node with
some data in it and you have left and right subtrees that need to be printed. In a pre-
order traversal you handle the root node first, which means you'd print out the data
for the root. You can include a space to separate it from other values on the line of
output:
private void printPreorder(IntTreeNode root) {
if (root != null) {
System.out.print(" " + node.data);
...
}
}
What do you do after you print the data for this node? You want to print the left
subtree in a preorder manner and then print the right subtree in a preorder manner:
private void printPreorder(IntTreeNode root) {
if (root != null) {
System.out.print(" " + node.data);
// then print left subtree in a preorder manner
Search WWH ::




Custom Search