I have implemented the following code to print a binary search tree in level order.
public void printLevelOrder(int depth) {
for (int i = 1; i <= depth; i++) {
printLevel(root, i);
}
}
public void printLevel(BinaryNode<AnyType> t, int level) {
if (t == null) {
return;
}
if (level == 1) {
System.out.print(t.element);
} else if (level > 1) {
printLevel(t.left, level - 1);
printLevel(t.right, level - 1);
}
}
I am trying to figure out how to improve my code to have it print out in a certain format.
As an example, given a tree
1
/ \
2 3
/ / \
4 5 6
Currently it prints like so:
123456
I am looking for it to print as follows:
Level 0: 1
Level 1: 2 3
Level 2: 4 5 6