AlgoTales · Roadmap

BFS / level-order traversal

Beginner · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Level-order (breadth-first) traversal visits a tree one row at a time: the top, then everything one step down, then two steps down, and so on. A queue, meaning a line where the first in is served first, keeps the order.

Practical use cases

  • Web app: People you may know. A social app wants to suggest friends. It first looks at your direct friends, then friends of friends, then the next ring out, stopping after two rings. Walking ring by ring means the closest people show up first, and it never has to scan the whole network.
  • Web app: Org chart shown level by level. An HR portal draws the company chart with the CEO at the top, then directors, then managers. Level-order gives each row as a ready list, so the page can render one horizontal band per level without extra sorting. Teams of thousands render in a single pass.
  • System: Shortest path and broadcast. A maze solver or a metro route finder that counts the fewest stops uses this ring-by-ring spread, so the first time it reaches the destination is already the shortest. Network broadcasts also spread this way, hop by hop.

The story: The Chai Stall Queue

Raju's chai stall was famous at the railway station, and at 8 a.m. there was always a long queue. Raju served in strict order: the person at the front of the queue got their chai first, and any friends they brought along joined the back of the queue.

One morning Mira, standing near the stall, noticed something beautiful. Suppose Raju serves the first customer, Mr. Kapoor, who brought two colleagues. They go to the back. Next Raju serves the second customer, who brought one friend; the friend goes to the back too. By the end, all of Mr. Kapoor's generation were served before the colleagues' guests.

"That is a tree!" shouted Mira. "The first person is the root, their guests are children, the guests' friends are grandchildren." And the queue serves the tree one whole row at a time, top to bottom, left to right.

Raju laughed: "I never knew I was running a computer science algorithm." That is breadth-first search, or level-order traversal: visit everyone at the same distance from the root before going one level deeper, using a queue.

How to spot this problem, and where you need it

You need to process things in order of closeness to a starting point, or show a hierarchy row by row, and a plain recursive walk gives you depth-first order instead.

Signs you need it

  • The task says "level by level", "row by row", "nearest first", "minimum number of steps" or "shortest path with equal costs".
  • Your recursive code reaches a very deep, distant item first while the user expects the nearest results at the top.
  • You are tracking a "depth" variable by hand to group items by row, which is a hint you want a queue.

Where to use it in a project

  • Rendering menus, org charts and category trees one level at a time, maybe loading deeper levels only on click.
  • Friend or follower suggestions limited to "friends of friends" and finding the fewest hops between two users.

The solution

Put the starting node in a queue. Repeat: take the front node, process it, and add its children to the back of the queue. Because newcomers always line up behind existing items, all items of one level are finished before any of the next level begin. To group by row, count how many items are in the queue at the start of each round and process exactly that many.

Payoff: Before: results in deep-first order and no easy way to stop at 2 hops. After: nearest people first, stop after any level you like.

Explain it like I am 8

Drop a pebble in a pond. The ripple spreads in rings: first the ring closest to the pebble, then the next ring out, and so on. Level-order walks the tree in rings. A queue keeps the order: whoever got in line first gets visited first.

How it works, step by step

  1. Put the root at the back of a queue.
  2. Take the front node out and visit it.
  3. Put its left child and then its right child at the back of the queue (if they exist).
  4. Repeat until the queue is empty: nodes come out level by level, left to right.
  5. To know which level you are on, process the queue in batches: note its current size, then handle exactly that many nodes as one level.

The code in four languages

PHP

<?php
class TreeNode {
    public ?TreeNode $left = null;
    public ?TreeNode $right = null;
    public function __construct(public int $val) {}
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree(): TreeNode {
    $root = new TreeNode(1);
    $root->left = new TreeNode(2);
    $root->right = new TreeNode(3);
    $root->left->left = new TreeNode(4);
    $root->left->right = new TreeNode(5);
    $root->right->right = new TreeNode(6);
    $root->left->right->left = new TreeNode(7);
    return $root;
}

// Level order with a queue. Returns one array per level.
function levelOrder(?TreeNode $root): array {
    if ($root === null) return [];
    $levels = [];
    $queue = [$root];
    while ($queue) {
        $size = count($queue);              // exactly the nodes of this level
        $level = [];
        for ($i = 0; $i < $size; $i++) {
            $node = array_shift($queue);    // take from the FRONT
            $level[] = $node->val;
            if ($node->left)  $queue[] = $node->left;    // add to the BACK
            if ($node->right) $queue[] = $node->right;
        }
        $levels[] = $level;
    }
    return $levels;
}

$levels = levelOrder(sampleTree());
echo json_encode($levels) . PHP_EOL;                        // [[1],[2,3],[4,5,6],[7]]
echo implode(' ', array_merge(...$levels)) . PHP_EOL;       // 1 2 3 4 5 6 7

JavaScript

class TreeNode {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}

// The example tree:      1
//                      /   \
//                     2     3
//                    / \     \
//                   4   5     6
//                      /
//                     7
function sampleTree() {
  const root = new TreeNode(1);
  root.left = new TreeNode(2);
  root.right = new TreeNode(3);
  root.left.left = new TreeNode(4);
  root.left.right = new TreeNode(5);
  root.right.right = new TreeNode(6);
  root.left.right.left = new TreeNode(7);
  return root;
}

// Level order with a queue. Returns one array per level.
function levelOrder(root) {
  if (root === null) return [];
  const levels = [];
  const queue = [root];
  while (queue.length) {
    const size = queue.length;            // exactly the nodes of this level
    const level = [];
    for (let i = 0; i < size; i++) {
      const node = queue.shift();         // take from the FRONT
      level.push(node.val);
      if (node.left) queue.push(node.left);     // add to the BACK
      if (node.right) queue.push(node.right);
    }
    levels.push(level);
  }
  return levels;
}

const levels = levelOrder(sampleTree());
console.log(JSON.stringify(levels));                  // [[1],[2,3],[4,5,6],[7]]
console.log(levels.flat().join(' '));                 // 1 2 3 4 5 6 7

Java

import java.util.*;
import java.util.stream.*;

public class Main {
    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    // The example tree:      1
    //                       /   \
    //                      2     3
    //                     / \     \
    //                    4   5     6
    //                       /
    //                      7
    static TreeNode sampleTree() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);
        root.left.right.left = new TreeNode(7);
        return root;
    }

    // Level order with a queue. Returns one list per level.
    static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        if (root == null) return levels;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();                 // exactly the nodes of this level
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();        // take from the FRONT
                level.add(node.val);
                if (node.left != null) queue.add(node.left);     // add to the BACK
                if (node.right != null) queue.add(node.right);
            }
            levels.add(level);
        }
        return levels;
    }

    public static void main(String[] args) {
        List<List<Integer>> levels = levelOrder(sampleTree());
        System.out.println(levels.toString().replace(" ", ""));   // [[1],[2,3],[4,5,6],[7]]
        System.out.println(levels.stream().flatMap(List::stream)
                .map(String::valueOf).collect(Collectors.joining(" ")));   // 1 2 3 4 5 6 7
    }
}

Go

package main

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
)

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// The example tree:      1
//
//	   /   \
//	  2     3
//	 / \     \
//	4   5     6
//	   /
//	  7
func sampleTree() *TreeNode {
	root := &TreeNode{Val: 1}
	root.Left = &TreeNode{Val: 2}
	root.Right = &TreeNode{Val: 3}
	root.Left.Left = &TreeNode{Val: 4}
	root.Left.Right = &TreeNode{Val: 5}
	root.Right.Right = &TreeNode{Val: 6}
	root.Left.Right.Left = &TreeNode{Val: 7}
	return root
}

// levelOrder walks the tree with a queue. It returns one slice per level.
func levelOrder(root *TreeNode) [][]int {
	levels := [][]int{}
	if root == nil {
		return levels
	}
	queue := []*TreeNode{root}
	for len(queue) > 0 {
		size := len(queue) // exactly the nodes of this level
		level := []int{}
		for i := 0; i < size; i++ {
			node := queue[0] // take from the FRONT
			queue = queue[1:]
			level = append(level, node.Val)
			if node.Left != nil {
				queue = append(queue, node.Left) // add to the BACK
			}
			if node.Right != nil {
				queue = append(queue, node.Right)
			}
		}
		levels = append(levels, level)
	}
	return levels
}

// joinInts glues the numbers together with a separator.
func joinInts(xs []int, sep string) string {
	parts := make([]string, len(xs))
	for i, v := range xs {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, sep)
}

func main() {
	levels := levelOrder(sampleTree())
	text, _ := json.Marshal(levels)
	fmt.Println(string(text)) // [[1],[2,3],[4,5,6],[7]]
	flat := []int{}
	for _, level := range levels {
		flat = append(flat, level...)
	}
	fmt.Println(joinInts(flat, " ")) // 1 2 3 4 5 6 7
}

Time: O(n) · Extra space: O(w). Each node enters and leaves the queue once. The queue holds at most one level at a time, so w is the widest level of the tree.

Watch out for

  • Using a stack instead of a queue; that quietly turns BFS into DFS.
  • Reading queue.length inside the loop instead of saving it first. The queue keeps changing, so your level boundaries go wrong.
  • Using array_shift / shift() on huge arrays: it can be slow (re-indexing). Use a pointer index or a real queue structure for big inputs.

Quick check

  1. Which data structure powers level-order traversal?
    • Sorted array
    • Stack
    • Queue
  2. What is the level-order of our example tree?
    • 1 2 4 5 7 3 6
    • 1 2 3 4 5 6 7
    • 4 7 5 2 6 3 1
  3. Why save the queue size at the start of each level?
    • To know how many nodes belong to that level
    • To make the queue smaller
    • To sort the values