0

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.

  • 2
    Print out newlines and complement the function with a second parameter `int indentLevel`. Increment it in the recursive calls. Choose the actual number of characters that make up a new indentation level and the indentation string at will. – collapsar Apr 14 '20 at 00:20

1 Answers1

1

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);
}
Joni
  • 108,737
  • 14
  • 143
  • 193