Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing Level Order Binary Search Tree Formatting

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
like image 692
ILostMySpoon Avatar asked Nov 01 '12 23:11

ILostMySpoon


People also ask

What is the order of a binary search tree?

A BST can be traversed through three basic algorithms: inorder, preorder, and postorder tree walks. Inorder tree walk: Nodes from the left subtree get visited first, followed by the root node and right subtree. Preorder tree walk: The root node gets visited first, followed by left and right subtrees.

How do you print nodes of tree level wise?

Algorithm to print nodes at given levelIf level of current node is equal to L then we will print it on screen else continue pre order traversal. If node is equal to NULL, return. If level of node is equal to L, then print node and return. Recursively traverse left and right sub trees at level L + 1.


1 Answers

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 
like image 95
Aziz Avatar answered Oct 21 '22 04:10

Aziz