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 queueSize.
Now while queueSize>0, take out the nodes and print it and add their children into the queue.
Note, in the diagram we are calling levelNodes = queueSize.
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
It is obvious that this problem can be solve by using a queue. However, if we use one queue we can not track when each level starts. So we use two queues to track the current level and the next level.
I think that the recursive way of traversal is truly not recursive, it eventually relies on iterative steps over the height of the tree and the recursion can only be used in identifying the correct level and printing it.
classSolution {
public List<List<Integer>>levelOrder(TreeNode root) {
List<List<Integer>> levels =new ArrayList<>();
if (root ==null) {
return levels;
}
helper(root, levels, 0);
return levels;
}
publicvoidhelper(TreeNode root, List<List<Integer>> ans, int level) {
if (root ==null) {
return;
}
if (res.size() < level + 1) {
ans.add(new ArrayList<>());
}
ans.get(level).add(root.val);
helper(root.left, ans, level + 1);
helper(root.right, ans, level + 1);
}
}
As we can see the for loop runs for O(H) time where H is the height of the tree. Each of these H calls to the printCurrentLevel routine takes O(H) * O(2K) time as in the previous iterative way and the same justification holds true for this algorithm as well.