Blind 75
30 / 75Free practice

Binary Tree Level Order Traversal

Medium · Trees

Jump to code

Return a binary tree’s values grouped by depth, from the root level downward and left to right within each level.

Examples

Example 1

root = [3,9,20,null,null,15,7]

Output: [[3],[9,20],[15,7]]

Example 2

root = [1]

Output: [[1]]

Constraints

  • 0 <= The number of nodes in the tree <= 1000
  • -1000 <= Node.val <= 1000

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

Snapshot the queue size before processing a level.

Asked in real interviews

Candidates reported versions of Binary Tree Level Order Traversal from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    3,
    9,
    20,
    null,
    null,
    15,
    7
  ]
]
Expected
[
  [
    3
  ],
  [
    9,
    20
  ],
  [
    15,
    7
  ]
]
Case 2
Input
[
  [
    1
  ]
]
Expected
[
  [
    1
  ]
]
Case 3
Input
[
  []
]
Expected
[]
Case 4
Input
[
  [
    1,
    null,
    2,
    3
  ]
]
Expected
[
  [
    1
  ],
  [
    2
  ],
  [
    3
  ]
]
Case 5
Input
[
  [
    1,
    2,
    3,
    4,
    null,
    null,
    5
  ]
]
Expected
[
  [
    1
  ],
  [
    2,
    3
  ],
  [
    4,
    5
  ]
]

Drafts are saved per language in this browser when storage is available.