I have the following method to recursively perform a preorder traversal of a ternary tree but having difficulty printing it in a certain manner.
public void preOrder(Node node) {
if (node == null) {
return;
}
System.out.print(" " + node.data);
preOrder(node.left);
preOrder(node.middle);
preOrder(node.right);
}
Output: Root LeftChild LeftChildA LeftChildB LeftChildC MiddleChild RightChild
Desired Output:
Root
Left
LeftChildA //Left child of left
LeftChildB //Middle child of left
LeftChildC //Right child of left
Middle
Right
I want to indent each level of the tree to make it more easier to visualize the tree's structure. Please help.
Add a parameter for how far the level should be indented. A string that has the exact number of characters you want to indent by works nicely. When you make the recursive calls, indent deeper.
public void preOrder(Node node) {
String initialIndent = ""; // Root level has no indentation
preOrderHelper(initialIndent, node);
}
public void preOrderHelper(String indent, Node node) {
if (node == null) {
return;
}
System.out.println(indent + node.data);
String newIndent = indent + " ";
preOrderHelper(newIndent, node.left);
preOrderHelper(newIndent, node.middle);
preOrderHelper(newIndent, node.right);
}