Binary Tree Level Order Traversal

Medium#102tree nodes

You get the root of a binary tree, possibly none. Return its values level by level: a list per level, from the top down and left to right within a level. Our example is the tree [7, 4, 9, 1, none, 6, 12, none, 3, 8] in level order — the answer is [[7], [4, 9], [1, 6, 12], [3, 8]].

input
root: a binary tree, written as on LeetCode: its values level by level, left to right, null for a missing child.
returns
Its values level by level: a list per level, from the root down, each one left to right; [] for an empty tree.
constraints
  • 0 ≤ the number of nodes ≤ 2000
  • −1000 ≤ Node.val ≤ 1000
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
function levelOrder(root) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more breadth-first search (bfs) problems

Pattern “Breadth-first search (BFS)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.