“I always wondered when DSA would help in real projects… until I built a user hierarchy system.”

When I was in college, I practiced Data Structures and Algorithms (DSA) for placements, especially tree traversal techniques. I never thought I’d use them outside interviews… until I built an application in PHP (CodeIgniter) that had a multi-level user hierarchy, just like an n-ary tree.
This article is about how I used level-order traversal (aka BFS) to solve a real problem in production.
Â
I had to build a system where users could have direct sub-users (referrals), and those users could have their own sub-users, and so on.
The structure looked like a tree:
User A
├── User B
│ ├── User D
│ └── User E
└── User C
└── User F
We needed to show users a breakdown of their network:
Â
I recalled from my DSA days that level-order traversal (Breadth First Search) is perfect for this.
The idea is simple:
Here’s a simplified version in Laravel-style PHP:
<?php
use SplQueue;
function getUsersByLevel(User $root, int $targetLevel)
{
$queue = new SplQueue();
$queue->enqueue([$root, 0]);
$usersAtLevel = [];
while (!$queue->isEmpty()) {
[$user, $level] = $queue->dequeue();
if ($level === $targetLevel) {
$usersAtLevel[] = $user;
}
if ($level < $targetLevel) {
foreach ($user->children as $child) {
$queue->enqueue([$child, $level + 1]);
}
}
}
return $usersAtLevel;
}
DSA is not just for interviews.
If you understand the right tools and structures, you can write elegant solutions even in practical applications!
Your email address will not be published. Required fields are marked *