Typorithm · medium

Level Order Traversal

level-order-traversaltreesbfsqueuelevels
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Level Order Traversal

0%

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.

01

Queue seeded with the root.

02

Freeze size per level.

03

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. BFS queue

Start the queue with the root node.

const queue = [root]

2. Freeze level size

Capture the count before adding the next level's children.

const size = queue.length

3. Dequeue front

Process nodes in first-in-first-out order.

const node = queue.shift()

4. Enqueue children

Children join the back for the next level.

if (node.left !== null) queue.push(node.left)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Level Order Traversal: Lesson & Practice · Typorithm | ApplyDjinn