1. BFS queue
Start the queue with the root node.
const queue = [root]Typorithm · medium
Step 1 of 8 · intro card
Trees
Use a queue to visit nodes level by level, freezing each level's size before enqueuing its children.
BFS visits a tree top-down, one full level at a time.
A queue holds the current frontier; the captured size marks where this level ends.
Each node is dequeued, recorded, and its children enqueued for the next sweep.
Queue seeded with the root.
Freeze size per level.
Enqueue children for next level.
function levelOrder(root) {
const result = [];
if (root === null) {
return result;
}
const queue = [root];
while (queue.length > 0) {
const level = [];
const size = queue.length;
for (let i = 0; i < size; i += 1) {
const node = queue.shift();
level.push(node.val);
if (node.left !== null) queue.push(node.left);
if (node.right !== null) queue.push(node.right);
}
result.push(level);
}
return result;
}Connect each part of the code to the concept before you type.
Start the queue with the root node.
const queue = [root]Capture the count before adding the next level's children.
const size = queue.lengthProcess nodes in first-in-first-out order.
const node = queue.shift()Children join the back for the next level.
if (node.left !== null) queue.push(node.left)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.