Binary Tree Level Order Traversal - Problem

You're given the root of a binary tree, and your task is to return the level order traversal of its nodes' values. This means you need to visit all nodes level by level, from left to right.

Think of it like reading a family tree or an organizational chart - you start at the top (root), then read all nodes at the second level from left to right, then all nodes at the third level from left to right, and so on.

Example: For a tree with root 3, left child 9, and right child 20 (where 20 has children 15 and 7), the level order traversal would be [[3], [9, 20], [15, 7]].

The result should be a 2D array where each inner array represents one level of the tree.

Input & Output

example_1.py โ€” Python
$ Input: root = [3,9,20,null,null,15,7]
โ€บ Output: [[3],[9,20],[15,7]]
๐Ÿ’ก Note: Level 0 has node 3, Level 1 has nodes 9 and 20, Level 2 has nodes 15 and 7
example_2.py โ€” Python
$ Input: root = [1]
โ€บ Output: [[1]]
๐Ÿ’ก Note: Tree with only root node results in single level with one element
example_3.py โ€” Python
$ Input: root = []
โ€บ Output: []
๐Ÿ’ก Note: Empty tree returns empty result

Visualization

Tap to expand
Level Order Traversal: Floor by Floor3Floor 0 (Level 0)Result: [3]920Floor 1 (Level 1)Result: [9, 20]157Floor 2 (Level 2)Result: [15, 7]Each floor is completely processed before moving to the next floor
Understanding the Visualization
1
Start at Root
Begin with the root node in your queue - this is floor 0 with 1 person
2
Process Current Level
Take photos of all people on current floor, then send their children to the next floor down
3
Move to Next Level
Move to the next floor (next level) and repeat the process
4
Continue Until Empty
Keep going until there are no more floors to photograph
Key Takeaway
๐ŸŽฏ Key Insight: Use a queue to process one complete level at a time, ensuring perfect level-by-level traversal in optimal O(n) time

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Visit each node exactly once during BFS traversal

n
2n
โœ“ Linear Growth
Space Complexity
O(w)

Queue stores at most w nodes, where w is maximum width of tree

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in tree is in the range [0, 2000]
  • Node values are in the range [-1000, 1000]
  • Follow up: Can you solve this both recursively and iteratively?
Asked in
Amazon 65 Microsoft 45 Google 38 Meta 32 Apple 28
125.0K Views
Very High Frequency
~15 min Avg. Time
2.9K 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