Facebook PixelBinary Tree Level Order Traversal — Coding Practice
Binary Tree Level Order TraversalMedium

Binary Tree Level Order Traversal

Medium 12.1k65% acceptance
TreeBreadth-First SearchBinary Tree

Given the root of a binary tree, return its node values grouped by level, from top to bottom. Within each level read the values left to right.

Return an array of arrays: the first inner array is the root's level, and so on. An empty tree returns [].

The tree is given in level-order (TreeNode with { val, left, right }, null for a missing child).

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Level 0 is [3], level 1 is [9,20], level 2 is [15,7].
Example 2
Input: root = [1]
Output: [[1]]
Example 3
Input: root = []
Output: []
No nodes, so there are no levels.
Constraints
  • The number of nodes is in the range [0, 2000].
  • -1000 ≤ Node.val ≤ 1000
Asked atAmazonMicrosoftMetaLinkedIn
JavaScript
Loading editor…
Case 1
[3,9,20,null,null,15,7]
expected: [[3],[9,20],[15,7]]
Case 2
[1]
expected: [[1]]
Case 3
[]
expected: []
Case 4
[1,2,3,4,5,6,7]
expected: [[1],[2,3],[4,5,6,7]]
Case 5
[1,null,2,null,3]
expected: [[1],[2],[3]]
Case 6
[0,-1,1]
expected: [[0],[-1,1]]