CodeSpeek

Binary Tree Level Order Traversal

Medium · Trees

You are given the root of a binary tree. Group the node values by their depth from the root and return a list of these groups, ordered from the topmost depth down to the deepest, with each group listing the values in left-to-right order at that depth. An empty tree should produce an empty list.

Examples

Input:  root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Why:    Node 3 is alone at depth 0, nodes 9 and 20 sit at depth 1, and nodes 15 and 7 sit at depth 2.
Input:  root = [1]
Output: [[1]]
Why:    A single node forms one level containing just itself.
Input:  root = []
Output: []
Why:    An empty tree has no levels at all.

Constraints

0 <= number of nodes <= 2000, -1000 <= Node.val <= 1000

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Binary Tree Level Order Traversal

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Binary Tree Level Order Traversal. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.