Print Binary Tree level by level with new line
  • Posted: 4 years ago
  • Updated: 3 years ago
  • Edit
  • answers (1)
  • views (4438)

Modify your algorithm in Print Binary Tree level by level to print the nodes in a new line for each level.


Posted Answers

We can print the binary tree with nodes in a new line for each level by using two \( queue \)s. The first queue will hold the binary tree at each level (like in Print Binary Tree level by level ) and the second queue will hold the number of current level. After finishing the printing of the nodes in one level we are inserting the new line and increasing the number of level by \( 1 \).

public static void printBinaryTreeByLevelNewLine(Node node) {

Queue queue1 = new LinkedList ();
Queue queue2 = new LinkedList ();
queue1.add(node);
queue2.add(0);

int lastLevel= 0;
while (queue.size() > 0) {
Node currentNode = queue1.remove();
int level = queue2.remove();

if(level! = lastLevel){
System.out.println();
lastLevel = level;
}

System.out.println(currentNode.value.toString() + " ");

if(currentNode.left! = null){
queue1.add(currentNode.left);
queue2.add(level+1);
}

if(currentNode.right! = null ){
queue1.add(currentNode.right);
queue2.add(level+1);
}
}

}

You need to Sign In to post your solution.