Binary Tree Level Order Traversal
Examples
Example 1:
Input: root = [1,2,3,4,5,6,7]
Output: [[1],[2,3],[4,5,6,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Example 1:
Input: root = [1,2,3,4,5,6,7]
Output: [[1],[2,3],[4,5,6,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Given a binary tree root, return the level order traversal of it as a nested list, where each sublist contains the values of nodes at a particular level in the tree, from left to right.
0 <= The number of nodes in the tree <= 1000-1000 <= Node.val <= 1000Use breadth-first search with a queue. For each level, process exactly the current queue size, collecting node values and enqueueing their children. This naturally groups nodes by level and handles empty trees.
BFS visits nodes in increasing depth order. By processing the queue in fixed-size layers, we collect exactly the nodes from one level before moving to the next, producing the required nested list structure.
O(n)O(n)class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> 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 result