Given the root of a binary tree, display the node values at each level. Node values for all levels should be displayed on separate lines. Let’s take a look at the below binary tree.
The runtime complexity of this solution is linear, O(n)O(n).
The memory complexity of this solution is linear, O(n)O(n).
Initialize a queue, queue, with the root node.
Iterate over the queue until it’s empty:
For each level, calculate the size (level_size) of the queue.
Initialize an empty list level_nodes.
Iterate level_size times:
Dequeue a node from the queue.
Append the value of the dequeued node in level_nodes.
Enqueue the left child and the right child of the dequeued node in queue, if they exist.
Convert level_nodes to a comma-separated string and store it in result.
Return the result.
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!