Bitpath

Boss lesson · Unit 01

Level by level

Breadth-first traversal with a queue, grouped by level

12 exercisesabout 3 min

What you practise

  • Breadth-first traversal with a queue
  • Grouping by level
  • Depth two ways

Try a question from this lesson

Pick one

Depth-first search dives down one branch. To visit a tree level by level, nodes must come back in the order they were discovered. Which structure does that?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Breadth-first search

Put the root in a queue. Then repeat: take the node at the front, handle it, and add its children at the back.

Children always join behind everything already waiting, so the tree is visited top to bottom, left to right.

from collections import deque

def bfs(root):
    q = deque([root])
    while q:
        node = q.popleft()
        print(node.val)
        if node.left:
            q.append(node.left)
        if node.right:
            q.append(node.right)
function bfs(root) {
  const q = [root];
  let head = 0;
  while (head < q.length) {
    const node = q[head++];
    console.log(node.val);
    if (node.left) q.push(node.left);
    if (node.right) q.push(node.right);
  }
}
function bfs(root: Node): void {
  const q: Node[] = [root];
  let head = 0;
  while (head < q.length) {
    const node = q[head++];
    console.log(node.val);
    if (node.left) q.push(node.left);
    if (node.right) q.push(node.right);
  }
}

Python notedeque.popleft() is O(1). list.pop(0) would shift every remaining item: O(n) per step.

JavaScript noteq[head++] reads the front and moves a head index forward. q.shift() also works, but it is O(n) on a long array.

TypeScript noteq: Node[] has no null in it: the if checks make sure only real nodes are ever pushed.

Concept

The boss: group by level

The task: return a tree's values grouped by level, like [[3], [9, 20], [15, 7]].

The trick is a snapshot. When a level starts, the queue holds exactly that level and nothing else. Note its size, remove that many nodes, and everything added meanwhile is the next level.

9 more exercises in the app

  • 3× type the answer
  • 1× order the lines
  • 1× fill the blanks
  • 2× multiple choice
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy