Tree: Level Order Traversal

  • + 0 comments

    Better clarity in the comments public static void levelOrder(Node root) { // Use ArrayDeque as the queue for level order traversal Queue nodeQueue = new ArrayDeque<>();

        // Start by offering the root node to the queue
        nodeQueue.offer(root);
    
        // Process nodes until the queue is empty
        while (nodeQueue.size() > 0) {
            // Remove the front element from the queue
            Node node = nodeQueue.poll();
    
            // Print the current node's data
            System.out.print(node.data + " ");
    
            // If the left child is not null, add it to the queue
            if (node.left != null) {
                nodeQueue.offer(node.left);
            }
    
            // If the right child is not null, add it to the queue
            if (node.right != null) {
                nodeQueue.offer(node.right);
            }
        }
    }