7

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
ILostMySpoon
  • 2,399
  • 2
  • 19
  • 25
  • Let the function `printLevel` returns the node number as a string instead of printing it immediately. Then, you can concatenate these strings in any format you want. – Aziz Nov 01 '12 at 23:17

1 Answers1

11

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 
Aziz
  • 20,065
  • 8
  • 63
  • 69