Breadth-First Search/Traversal in a Binary Tree

Breadth-First Search ( or Traversal) also know as Level Order Traversal.

What is Breadth First Search:

Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root and explores the neighbor nodes first, before moving to the next level neighbors. (Reference – Wiki)




  • Take a Empty Queue.
  • Start from the root, insert the root into the Queue.
  • Now while Queue is not empty,
    • Extract the node from the Queue and insert all its children into the Queue.
    • Print the extracted node.

Complete Code:

import java.util.LinkedList;
import java.util.Queue;
public class T_BFS {
public void levelOrderQueue(Node root) {
Queue<Node> q = new LinkedList<Node>();
if (root == null)
while (!q.isEmpty()) {
Node n = (Node) q.remove();
System.out.print(" " +;
if (n.left != null)
if (n.right != null)
public static void main(String[] args) throws java.lang.Exception {
Node root = new Node(5);
root.left = new Node(10);
root.right = new Node(15);
root.left.left = new Node(20);
root.left.right = new Node(25);
root.right.left = new Node(30);
root.right.right = new Node(35);
T_BFS i = new T_BFS();
System.out.println("Breadth First Search : ");
class Node {
int data;
Node left;
Node right;
public Node(int data) { = data;
this.left = null;
this.right = null;

view raw

hosted with ❤ by GitHub

Breadth First Search : 
 5 10 15 20 25 30 35