Tree Breadth First Search Cheat Sheet

You use a queue to go through the tree one level at a time. You finish all the nodes at one depth before you move down to the next.

Tree Breadth First Search cheat sheet preview

Unlock the full sheet below.

When to use it

  • The answer is grouped by level or depth.
  • You compare or connect nodes at the same depth.
  • DFS would also work here. BFS is easier because you get the nodes already grouped by depth.
  • The problem says 'level by level' or asks about each row of the tree.

What's on the sheet

The sheet has a code template you can reuse for every Tree Breadth First Search problem. It's split into four steps so you can see which part changes from problem to problem. It also shows how to spot the pattern, how fast it runs, the mistakes people often make and the variations you'll see in interviews.

How to get it

You'll need full access for this one. You unlock it by solving 3 of this pattern's problems. Only 2 of those problems are free.

Preview the Two Pointers sample to see a finished sheet first.