Since we need to traverse all the nodes of each level before moving onto the next level, we can use the Breadth First Search (BFS) technique to solve this problem. We can use a queue to efficiently traverse in BFS fashion.
Let’s see how we might implement this functionality:
Start by enqueuing the root node to the queue.
Iterate until the queue is empty.
During each iteration, first count the elements in the queue (let’s call it queue_size). We will have this many nodes in the current level.
Next, remove queue_size nodes from the queue and enqueue their value in a list to represent the current level.
After removing each node from the queue, insert all of its children into the queue. If the queue is not empty, repeat from step 3 for the next level.