Reputation: 1
How would one go about pre-order printing a binary tree with an indentation (3 spaces) for each subsequent level. At this point, I'm recursively printing out the tree by using a helper method, but I'm not sure how to go about coding the indentation. This is what I have so far:
public void print() {
printPreorder(root);
System.out.println();
}
private void printPreorder(BinaryTreenode<E> node) {
System.out.println(node.getData() + " ");
if (node.getLeft() != null) {
printPreorder(node.getRight());
}
if (node.getRight() != null) {
printPreorder(node.getRight());
}
}
My immediate thought was to put in a counter and have it increment each time the method is recursively called, and then indent three spaces for each increment, but I'm not sure that this is the best way to do this.
Upvotes: 0
Views: 5532
Reputation: 13922
You were heading in the right direction. Here's some general pseudocode:
void print(node) {
print(node, "")
}
private void print(node, indent) {
if(node is null) return
output(indent + node.data)
print(node.left, indent + " ")
print(node.right, indent + " ")
}
Upvotes: 1