Level Order Traversal Queue Algorithm

The Level Order Traversal Queue Algorithm is a tree traversal algorithm that visits the nodes in a binary tree in a breadth-first manner, meaning it processes nodes level by level, from left to right. This technique is also known as Breadth-First Search (BFS) traversal, as it visits all the nodes at a particular depth before moving on to the nodes at the next depth level. The algorithm mainly utilizes a queue data structure to keep track of the nodes to be processed at each level. The algorithm starts by enqueuing the root node of the binary tree. Then, while the queue is not empty, it dequeues the front node, processes (or visits) it, and enqueues its left and right children if they exist. This process continues until the queue becomes empty, which signifies that all the nodes in the tree have been visited. The Level Order Traversal Queue Algorithm is particularly useful in various applications, such as analyzing hierarchical data structures, determining the shortest path in a tree or graph, and solving certain types of tree-based problems.
package DataStructures.Trees;

import java.util.Queue;
import java.util.LinkedList;


/* Class to print Level Order Traversal */
public class LevelOrderTraversalQueue {

    /* Class to represent Tree node */
    class Node {
        int data;
        Node left, right;

        public Node(int item) {
            data = item;
            left = null;
            right = null;
        }
    }

    /* Given a binary tree. Print its nodes in level order
     using array for implementing queue  */
    void printLevelOrder(Node root) {
        Queue<Node> queue = new LinkedList<Node>();
        queue.add(root);
        while (!queue.isEmpty()) {
 
            /* poll() removes the present head.
            For more information on poll() visit 
            http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
            Node tempNode = queue.poll();
            System.out.print(tempNode.data + " ");

            /*Enqueue left child */
            if (tempNode.left != null) {
                queue.add(tempNode.left);
            }

            /*Enqueue right child */
            if (tempNode.right != null) {
                queue.add(tempNode.right);
            }
        }
    }
}

LANGUAGE:

DARK MODE: