Print nodes of every level from 1 to height by calling a function with given level
A recursive function is used to print nodes at a given level where we pass level - 1 in the recursive calls and the base case is to print the node when level is 1.
Output
1
2 3
4 5
[Expected Approach] Using Queue – O(n) Time and O(n) Space
If we take a closer look at the working of standard level order traversal, we can notice that after processing a every iteration, we have the nodes of the next level in the queue. Why? because when we do level order traversal, we push children of the current node after processing it.
Before beginning the standard queue based loop, we get the size of the queue to count the number of nodes and then run a loop to print those many nodes followed by a newline.