Level Order Traversal - Problem

Given the root of a binary tree, return the level order traversal of its nodes' values.

In level order traversal, we visit all nodes at depth 0 first, then all nodes at depth 1, then all nodes at depth 2, and so on.

Each level should be displayed on a separate line.

Example:

For the tree:

    3
   / \
  9  20
    /  \
   15   7

The level order traversal would be:

3
9 20
15 7

Input & Output

Example 1 — Basic Tree
$ 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 — Single Node
$ Input: root = [1]
Output: 1
💡 Note: Only one level with a single node
Example 3 — Left-Heavy Tree
$ Input: root = [1,2,3,4,null,null,5]
Output: 1 2 3 4 5
💡 Note: Level 0: [1], Level 1: [2,3], Level 2: [4,5]

Constraints

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

Visualization

Tap to expand
INPUTALGORITHMRESULT3920157Binary Tree StructureNodes: [3,9,20,null,null,15,7]1Start with root in queue2Process all nodes in level3Add children to queue4Repeat until queue emptyQueue Steps:Level 0: Queue=[3] → Output "3"Level 1: Queue=[9,20] → Output "9 20"Level 2: Queue=[15,7] → Output "15 7"Level Order Output:39 2015 7Each level onseparate lineKey Insight:BFS with queue naturally processes one complete level before moving to the next level,making it perfect for level order traversal of binary trees.TutorialsPoint - Level Order Traversal | BFS Queue Approach
Asked in
Google 42 Amazon 38 Microsoft 35 Facebook 28
28.5K Views
High Frequency
~15 min Avg. Time
980 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