BFS (Breadth-First Search) in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
#include <stdlib.h>
typedef struct N { int d; struct N *l, *r; } N;
N* n(int d) { N* t = malloc(sizeof(N)); t->d = d; t->l = t->r = NULL; return t; }

void bfs(N* r) {
    if (!r) return;
    N* q[100]; int f=0, b=0;
    q[b++] = r;
    while (f < b) {
        N* t = q[f++];
        printf("%d ", t->d);
        if (t->l) q[b++] = t->l;
        if (t->r) q[b++] = t->r;
    }
}

int main() {
    N* r = n(1);
    r->l = n(2); r->r = n(3);
    r->l->l = n(4); r->l->r = n(5);
    bfs(r);
}

C Output

Input:  
        1
       / \
      2   3
     / \
    4   5  

Output:  
Input: 1 2 3 4 5
Output: 1 2 3 4 5


C++ Program

#include <iostream>
#include <queue>
using namespace std;
struct N { int d; N *l, *r; N(int v): d(v), l(0), r(0) {} };
void bfs(N* r) {
    if (!r) return;
    queue<N*> q; q.push(r);
    while (!q.empty()) {
        N* t = q.front(); q.pop();
        cout << t->d << " ";
        if (t->l) q.push(t->l);
        if (t->r) q.push(t->r);
    }
}
int main() {
    N* r = new N(10);
    r->l = new N(6); r->r = new N(15);
    r->r->r = new N(20);
    bfs(r);
}

C++ Output

Input:  
       10
      /  \
     6   15
            \
            20

Output:  
Input: 10 6 15 20
Output: 10 6 15 20


JAVA Program

import java.util.*;
class N {
    int d; N l, r;
    N(int d) { this.d = d; }
}
public class Main {
    static void bfs(N r) {
        if (r == null) return;
        Queue<N> q = new LinkedList<>();
        q.add(r);
        while (!q.isEmpty()) {
            N t = q.poll();
            System.out.print(t.d + " ");
            if (t.l != null) q.add(t.l);
            if (t.r != null) q.add(t.r);
        }
    }
    public static void main(String[] a) {
        N r = new N(5);
        r.l = new N(2); r.r = new N(8);
        r.l.l = new N(1);
        bfs(r);
    }
}

JAVA Output

Input:  
        5
       / \
      2   8
     /
    1

Output:  
Input: 5 2 8 1
Output: 5 2 8 1


Python Program

from collections import deque
class N:
    def __init__(s, d): s.d, s.l, s.r = d, None, None
def bfs(r):
    if not r: return
    q = deque([r])
    while q:
        t = q.popleft()
        print(t.d, end=' ')
        if t.l: q.append(t.l)
        if t.r: q.append(t.r)

r = N(3)
r.l = N(1); r.r = N(5)
r.r.l = N(4)
bfs(r)

Python Output

Input:  
      3
     / \
    1   5
       /
      4 

Output:  
Input: 3 1 5 4
Output: 3 1 5 4


In-Depth Explanation
Example
Consider the example of C. We added nodes as:


        1
       / \
      2   3
     / \
    4   5

BFS visits level-by-level, hence print order is: 1 (root), followed by 2 and 3 (second level), then 4 and 5 (third level) → 1 2 3 4 5.

Real-Life Analogy
Consider a hospital queue. The receptionist receives patients one-at-a-time, not based on how deep their issue is, but based on when they arrive. Likewise, BFS uses a queue to visit tree nodes level-wise — not depth-wise.

Why It Matters
BFS is important when:

You need to process tree nodes level-wise (such as in tree visualizations)

Shortest path finding (such as in graphs)

Constructing game AI (decision trees level-wise)

Processing hierarchical data in breadth order (such as folder hierarchy or org charts)

It provides a big-picture view first, before zooming in — ideal for applications where nearness is more important than hierarchy.

Learning Insights
This illustrates:

How queues facilitate BFS traversal

Iterative vs recursive thinking (BFS is inherently iterative)

Effective memory usage for level-order processing

Neat isolation of logic with little code

You'll also see how recursion isn't always the better way — sometimes iteration with queue is more elegant and stack overflow free!

Interview & Real-World Usage
BFS is a favorite interview question and is commonly used in:

Minimum depth finding

Maze/shortest path solving

Level order printing or zigzag traversal

Any graph traversal that involves "breadth-first" logic

Real-world applications:
File system traversals

Web crawlers crawling web pages

AI search algorithms (such as Minimax)

Breadth-First Search (BFS) is one of the strongest tree traversal methods. It assists in exploring trees level-wise utilizing queues, and its real-world analogy makes it simple to understand for students. With these neat, short, and fully functional implementations in C, C++, Java, and Python, now you can comprehend how level-order traversal operates and how it varies from depth-based methods. BFS has applications in interviews and big applications like games, file systems, and shortest path algorithms.