Problem Statement in English

You’re given the root of a binary tree. Return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).


Approach

We can do this using a queue to keep track of the nodes at each level. We will start with the root node in the queue, and for each level, we will dequeue all nodes, record their values, and enqueue their children for the next level in a new queue.

And we’re done!


Solution in Python


class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root: return []
        
        q = deque([root])
        res = []

        while q:
            res.append([])
            next_q = []

            while q:
                node = q.popleft()
                res[-1].append(node.val)

                if node.left:
                    next_q.append(node.left)
                if node.right:
                    next_q.append(node.right)

            q = deque(next_q)

        return res

Complexity

  • Time: $O(n)$
    Since we are traversing all the nodes in the tree, the time complexity is linear with respect to the number of nodes, which is $O(n)$.

  • Space: $O(n)$
    Since we are storing the nodes of the tree in a queue, the space complexity is also linear with respect to the number of nodes, which is $O(n)$.


And we are done.