PracticeNeetCode ↗LeetCode ↗
Given the root of a binary tree, return the values of its nodes grouped level by level, from top to bottom.
Time: O(n) — Space: O(n)
from collections import deque
def levelOrder(root: TreeNode | None) -> list[list[int]]:
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
level = []
for _ in range(level_size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return resultHow the solution above works, piece by piece.
if not root: return []: an empty tree has no levels.queue = deque([root]): a queue gives nodes back in the order they were added, which is what keeps levels in order. deque.popleft() is O(1).while queue: one pass of this loop handles exactly one level.level_size = len(queue): read the size before popping. At this moment the queue holds only the current level; children added below belong to the next level and must not be counted.level_size nodes, add each value to level, and push its left and right children (if any) onto the back of the queue.result.append(level): one inner list per level. Every node is pushed and popped once: O(n) time, O(width) queue space.Running it on root = [3, 9, 20, null, null, 15, 7]:
len(queue) first fixes how many to pop; children added during the loop wait for the next round. Result: [[3], [9, 20], [15, 7]].