Problem
Given a binary tree, you have to print level order traversal of the tree (left child then right child) but every next level has to be printed in next line.
Example
If the given tree is
5
10 15
56 47 12 42
```Then the output should be
5
10 15
56 47 12 42
### Solution
Here is the approach:
1. Start with a root node. Add it to a new list.
2. Now add all the children of the elements present in the new list and print the element, after removing the element. Once the array is empty, print the new line.
Here is the code
public void getLevelOrderInNewLine(TreeNode root)
{
List next = new ArrayList();
next.add(root);
//actual function
levelOrder(next);
}
public void levelOrder(List n) {
List next = new ArrayList();
for (TreeNode t : n) {
if (t != null) {
System.out.print(t.getValue());
next.add(t.getLeftChild());
next.add(t.getRightChild());
}
}
System.out.println();
if(next.size() > 0)levelOrder(next);
}
**References**
* [https://stackoverflow.com/questions/2241513/java-printing-a-binary-tree-using-level-order-in-a-specific-format](https://stackoverflow.com/questions/2241513/java-printing-a-binary-tree-using-level-order-in-a-specific-format)See also
- Given an array filled with char elements, find the max length of continuous white space
- Find the longest oscillating subsequence
- Binary Tree Level-Order Traversal Using Depth First Search (DFS) [Not to USE BFS]
- BFS (Breadth first search ) OR Level Order Traversal on tree
- Print a Binary Tree in Zig Zag Level Order or spiral order