← All questions

Binary Tree Level Order Traversal

Medium Trees & Graphs

Given the root of a binary tree, return its level-order traversal: a list of levels, each level being the node values from left to right.

Examples

Input:        3
            /   \
           9     20            Output: [[3], [9,20], [15,7]]
                /  \
              15    7

Constraints

  • 0 <= number of nodes <= 2000.

Solution

Approach strategy: Level order is exactly a BFS. The subtlety is grouping the output per level.

Full worked solution, code, and complexity analysis available in the interactive view.

Related problems