Back to posts
Algorithms

How I Used Level-Order Tree Traversal from DSA in a Real-World PHP Application

I always wondered when DSA would actually help in a real project. Here's the story of how level-order tree traversal solved a multi-level referral hierarchy problem in production PHP.

May 6, 20253 min read

College DSA courses always felt abstract to me. Binary trees, BFS, queues - sure, I understood them for exams. But in real projects? I kept reaching for SQL joins and recursive functions instead.

That changed when I built a multi-level referral system.

The Problem

The system had users who could refer other users, who could refer other users, and so on. Classic MLM-style hierarchy. The requirement was to display users organized by their level in the tree - Level 1 (direct referrals), Level 2 (referrals of referrals), Level 3, etc.

In tree terminology: each user is a node, their referrals are child nodes, and the structure is an n-ary tree (each node can have multiple children).

I needed to retrieve all users at a specific depth level from a root node.

Why Level-Order Traversal (BFS)?

Depth-First Search (DFS / recursion) would give me users in the wrong order - I'd traverse all the way down one branch before processing siblings on the same level.

Level-order traversal (BFS) processes nodes level by level - exactly what I needed.

The algorithm:

  1. Start at the root user (enqueue them)
  2. Dequeue a user, enqueue all their direct referrals
  3. Track the current depth
  4. When depth matches the target level, collect those users

The PHP Implementation

PHP's SPL has a built-in SplQueue - perfect for this.

php
function getUsersByLevel(int $rootUserId, int $targetLevel): array
{
    $queue = new SplQueue();
    $queue->enqueue(['id' => $rootUserId, 'level' => 0]);
 
    $result = [];
 
    while (!$queue->isEmpty()) {
        ['id' => $userId, 'level' => $currentLevel] = $queue->dequeue();
 
        if ($currentLevel === $targetLevel) {
            $result[] = $userId;
            continue; // No need to go deeper
        }
 
        if ($currentLevel > $targetLevel) {
            break; // We've gone past the target level
        }
 
        // Fetch direct referrals from DB
        $children = DB::table('users')
            ->where('referred_by', $userId)
            ->pluck('id');
 
        foreach ($children as $childId) {
            $queue->enqueue(['id' => $childId, 'level' => $currentLevel + 1]);
        }
    }
 
    return $result;
}

What Made This Better Than Recursion?

Recursion would have meant:

  • Deep call stacks for large hierarchies
  • Harder to limit traversal at a specific level cleanly
  • Risk of stack overflow for very deep trees

BFS with a queue:

  • Processes nodes in the exact order needed (level by level)
  • Naturally terminates when the target level is reached
  • No stack overflow risk
  • Easier to reason about and test

Key Takeaway

DSA isn't just for interviews. The patterns - trees, queues, BFS, DFS - show up in real software problems disguised as "hierarchy display", "dependency resolution", "shortest path in a graph", etc.

The next time you find yourself fighting a recursive function to get data in the right order, ask: is this actually a traversal problem? The right data structure might make it trivial.

Tags: DSA, Algorithms, PHP, Trees, BFS, Level Order Traversal