Binary Tree Level Order Traversal

Easy
BFS

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).

A binary tree level order traversal visits all nodes at depth d before visiting nodes at depth d+1.

This is the most fundamental BFS problem - it directly implements the core concept of exploring a tree level by level using a queue.

Example 1

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Explanation: Level 0: [3], Level 1: [9, 20], Level 2: [15, 7]

Example 2

Input: root = [1]
Output: [[1]]
Explanation: Single node tree has only one level.

Example 3

Input: root = []
Output: []
Explanation: Empty tree returns empty result.

Constraints

  • The number of nodes in the tree is in the range [0, 2000]
  • -1000 <= Node.val <= 1000
Show Hints (4)
Hint 1: What data structure allows us to process nodes in the order they were discovered?
Hint 2: A queue processes elements in FIFO order - first discovered, first processed.
Hint 3: To separate levels, track how many nodes are in the current level before processing.
Hint 4: For each level, process exactly the number of nodes that were in the queue when the level started.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?