Solution by sneha29shukla

Approach #1 Recursive Solution (BFS) [Accepted]

Intuition

The intuition is simple BFS. We first find the height of the tree, and then for each level in the tree, keep adding the nodes to a list, which is added to a final list of lists, as required by the signature of the solution.

The time complexity can be O(n^2) in the worst case. That is because, the getNodesAtLevel function has a complexity of O(n) for a skewed tree of n nodes. In the worst case it would be O(n) + O(n - 1).... and hence, O(n^2).

Space complexity : The extra space for this solution comes only from the stack maintained by recursion.

Approach #2 Using a Queue [Accepted]

Algorithm

Create an empty queue and add root to it

While the queue is not null

For the current size of queue (contains previous level's nodes)

Poll the queue. Add the data of the polled node to a sublist.

Enqueue the polled node's children (first left then right children) to queue

Intuition

In each iteration of the outer while loop, we first check the current size of the queue (the size would give us the number of nodes added at the previous level. For eg, in the first iteration, the size of the queue would be 1 as only root has been added).

We then iterate till the size of the queue. This way, we remove the nodes from the queue from the previous level (as we are iterating till the size of the queue before we enqueued the current level's nodes and polling the queue) and add the current level's nodes.