Binary Tree Level Order Traversal

Medium~20 min

Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level).

Return the result as a list of lists, where each inner list contains the node values at that depth level.

Each node has a val (integer value), a left child, and a right child. Children may be null.

The tree is given as a level-order array where null represents a missing node. For example, [3,9,20,null,null,15,7] represents:

      3
     / \
    9  20
      /  \
     15   7

Examples

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Explanation: Level 0 has node 3. Level 1 has nodes 9 and 20. Level 2 has nodes 15 and 7.
Example 2
Input: root = [1]
Output: [[1]]
Explanation: A single-node tree has one level with one value.
Example 3
Input: root = []
Output: []
Explanation: An empty tree has no levels.

Constraints

  • The number of nodes in the tree is in the range [0, 2000]
  • -1000 <= Node.val <= 1000
  • Expected time complexity: O(n)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run