Printing Level Order Binary Search Tree Formatting

12,258

Instead of printing the values immediately inside the recursive function calls, use strings to hold the values. This will make it easier to manipulate the output.

public void printLevelOrder(int depth) {
    for (int i = 1; i <= depth; i++) {
        System.out.print("Level " + (i-1) + ": ");
        String levelNodes = printLevel(root, i);
        System.out.print(levelNodes + "\n");
    }
}

public String printLevel(BinaryNode<AnyType> t, int level) {
    if (t == null) {
        return "";
    }
    if (level == 1) {
        return t.element + " ";
    } else if (level > 1) {
        String leftStr = printLevel(t.left, level - 1);
        String rightStr = printLevel(t.right, level - 1);
        return leftStr + rightStr;
    }
    else // you need this to get it to compile
      return "";
}

Output:

Level 0: 1 
Level 1: 2 3 
Level 2: 4 5 6 
Share:
12,258
ILostMySpoon
Author by

ILostMySpoon

Updated on July 06, 2022

Comments

  • ILostMySpoon
    ILostMySpoon almost 2 years

    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