**Objective:** Given a Binary tree , Print each level of a tree in separate line.

**NOTE : This problem is very similar ” Create Linked Lists of all the nodes at each depth “**

**Input:** A binary tree

**Output: Each level of binary tree, in one line **

**Example:**

Level Order Traversal, Print each level in one line.

**Approach:**

**Naive Approach:**

- Get the height of the tree.
- Put a for loop for each level in tree.
- for each level in step 2, do pre order traversal and print only when height matches to the level.
- Look at the code for better explanation

**Time Complexity : O(N^2) – because each level you are traversing the entire tree.**

**Better Solution : Time Complexity – O(N)**

- Create a ArrayList of Linked List Nodes.
- Do the level order traversal using queue(Breadth First Search). Click here to know about how to level order traversal.
- For getting all the nodes at each level, before you take out a node from queue, store the size of the queue in a variable, say you call it as levelNodes.
- Now while levelNodes>0, take out the nodes and print it and add their children into the queue.
- After this while loop put a line break.

while(!q.isEmpty()){
levelNodes = q.size();
while(levelNodes>0){
Node n = (Node)q.remove();
System.out.print(" " + n.data);
if(n.left!=null) q.add(n.left);
if(n.right!=null) q.add(n.right);
levelNodes--;
}
System.out.println("");
}

*Since we had taken the queue size before we add new nodes, we will get the count at each level and after printing this count, put a line break, see the example below*

Level Order Traversal, Print each level in separate line.

**Complete Code:**

**Output**:

Output by Naive Approach :
5
10 15
20 25 30 35
Output by Better Approach :
5
10 15
20 25 30 35

__________________________________________________

**Top Companies Interview Questions..-**

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

__________________________________________________

### Like this:

Like Loading...

*Related*