Binary Tree Level Order Traversal - Problem

Given the root of a binary tree, return the level order traversal of its nodes' values. This means visiting nodes level by level, from left to right within each level.

For example, if we have a binary tree with root value 3, left subtree with values 9, and right subtree with values 20, 15, 7 (where 15 and 7 are children of 20), we should return [[3], [9, 20], [15, 7]].

Each sub-array represents one level of the tree, ordered from top to bottom.

Input & Output

Example 1 — Complete Binary Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
💡 Note: Level 0: [3], Level 1: [9,20], Level 2: [15,7]. We traverse left to right within each level.
Example 2 — Single Node
$ Input: root = [1]
Output: [[1]]
💡 Note: Only one node at level 0, so result is [[1]].
Example 3 — Empty Tree
$ Input: root = []
Output: []
💡 Note: Empty tree has no levels, return empty array.

Constraints

  • The number of nodes in the tree is in the range [0, 2000]
  • -1000 ≤ Node.val ≤ 1000

Visualization

Tap to expand
Binary Tree Level Order Traversal INPUT 3 9 20 15 7 Level 0 Level 1 Level 2 root = [3,9,20,null,null,15,7] Tree with 3 levels, 5 nodes ALGORITHM (BFS) 1 Initialize Queue Add root to queue 3 2 Process Level 0 Dequeue 3, add children 9 20 3 Process Level 1 Dequeue 9,20, add children 15 7 4 Process Level 2 Dequeue 15,7, queue empty Queue Empty OK - All levels processed! FINAL RESULT Level Order Traversal: Level 0: 3 Level 1: 9 20 Level 2: 15 7 Output: [[3],[9,20],[15,7]] Time: O(n) Space: O(n) OK Key Insight: BFS naturally processes nodes level by level. Use a queue to track nodes at each level. For each level, process all nodes currently in queue, then add their children for the next level. TutorialsPoint - Binary Tree Level Order Traversal | BFS Approach
Asked in
Facebook 65 Amazon 58 Microsoft 42 Google 35
221.0K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen