Level order traversal (BFS)
Medium TimeO(n) SpaceO(n)
Level order reads a tree in rows: the root, then everything one step below it, then everything two steps below, with each row kept separate. Given the root of a binary tree, return those rows, each as its own array. Within a row the nodes are read left to right, and an empty tree produces an empty list.
Examples
Example 1
- Input
- root = buildTree()
- Output
- Row by row: the root
[[4],[2,7],[1,3,6,9]]4, then2, 7, then the four leaves left to right.
Example 2
- Input
- root = buildTree().left
- Output
- The left subtree on its own has two rows:
[[2],[1,3]]2, and then1, 3.
The Code
function buildTree() {
return {
val: 4,
left: { val: 2, left: { val: 1, left: null, right: null }, right: { val: 3, left: null, right: null } },
right: { val: 7, left: { val: 6, left: null, right: null }, right: { val: 9, left: null, right: null } }
};
}
function levelOrder(root) {
const levels = [];
let current = root === null ? [] : [root];
while (current.length > 0) {
const values = [];
const next = [];
for (let i = 0; i < current.length; i++) {
const node = current[i];
values.push(node.val);
if (node.left !== null) next.push(node.left);
if (node.right !== null) next.push(node.right);
}
levels.push(values);
current = next;
}
return levels;
}
levelOrder(buildTree());Done
More like this
All binary trees examples (9) →- Inorder traversal Left subtree, then the node, then right — a BST comes out sorted.
- Max tree depth A node is one deeper than its deepest child.
- Invert a tree Swap every node’s children, all the way down.
- Validate a BST Every node needs a valid range, not just a valid parent.
- Lowest common ancestor Walk down until the two targets fall on opposite sides.
- Tree diameter Each node returns a depth upward while quietly recording a width.