### Print Binary Tree level by level with new line node queue root binarytree    Posted: 5 years ago Updated: 4 years ago Edit answers (1) views (5629)

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

 Posted: 5 years ago 0 0 Edit 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); } } }