Bird
Raised Fist0
DSA Javaprogramming~20 mins

Tree Traversal Level Order BFS in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Level Order BFS Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Level Order Traversal on a Simple Tree
What is the output of the following Java code performing level order traversal (BFS) on the given binary tree?
DSA Java
class Node {
    int val;
    Node left, right;
    Node(int val) { this.val = val; }
}

public class Main {
    public static void levelOrder(Node root) {
        if (root == null) return;
        java.util.Queue<Node> queue = new java.util.LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Node current = queue.poll();
            System.out.print(current.val + " ");
            if (current.left != null) queue.add(current.left);
            if (current.right != null) queue.add(current.right);
        }
    }

    public static void main(String[] args) {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.left.right = new Node(5);
        levelOrder(root);
    }
}
A4 5 2 3 1
B1 3 2 5 4
C1 2 3 4 5
D1 2 4 5 3
Attempts:
2 left
💡 Hint
Remember, level order traversal visits nodes level by level from left to right.
❓ Predict Output
intermediate
2:00remaining
Output of Level Order Traversal with Null Children
What will be printed by this Java code performing level order traversal on a binary tree where some nodes have only one child?
DSA Java
class Node {
    int val;
    Node left, right;
    Node(int val) { this.val = val; }
}

public class Main {
    public static void levelOrder(Node root) {
        if (root == null) return;
        java.util.Queue<Node> queue = new java.util.LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Node current = queue.poll();
            System.out.print(current.val + " ");
            if (current.left != null) queue.add(current.left);
            if (current.right != null) queue.add(current.right);
        }
    }

    public static void main(String[] args) {
        Node root = new Node(10);
        root.left = new Node(20);
        root.left.right = new Node(40);
        root.right = new Node(30);
        levelOrder(root);
    }
}
A10 30 20 40
B10 20 30 40
C10 20 40 30
D10 40 20 30
Attempts:
2 left
💡 Hint
Check the order nodes are added to the queue: left child first, then right child.
🔧 Debug
advanced
2:00remaining
Identify the Error in Level Order Traversal Implementation
What error will this Java code produce when performing level order traversal on a binary tree?
DSA Java
class Node {
    int val;
    Node left, right;
    Node(int val) { this.val = val; }
}

public class Main {
    public static void levelOrder(Node root) {
        java.util.Queue<Node> queue = new java.util.LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Node current = queue.poll();
            System.out.print(current.val + " ");
            if (current.left != null) queue.add(current.left);
            if (current.right != null) queue.add(current.right);
        }
    }

    public static void main(String[] args) {
        Node root = null;
        levelOrder(root);
    }
}
AInfinite loop
BNo output, program ends normally
CSyntaxError
DNullPointerException
Attempts:
2 left
💡 Hint
Check what happens when root is null and you add it to the queue.
🚀 Application
advanced
2:00remaining
Number of Nodes at Each Level Using Level Order Traversal
Given the following Java code, what is the output showing the count of nodes at each level of the binary tree?
DSA Java
class Node {
    int val;
    Node left, right;
    Node(int val) { this.val = val; }
}

public class Main {
    public static void countNodesPerLevel(Node root) {
        if (root == null) return;
        java.util.Queue<Node> queue = new java.util.LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            System.out.print(levelSize + " ");
            for (int i = 0; i < levelSize; i++) {
                Node current = queue.poll();
                if (current.left != null) queue.add(current.left);
                if (current.right != null) queue.add(current.right);
            }
        }
    }

    public static void main(String[] args) {
        Node root = new Node(5);
        root.left = new Node(3);
        root.right = new Node(8);
        root.left.left = new Node(1);
        root.left.right = new Node(4);
        root.right.right = new Node(9);
        countNodesPerLevel(root);
    }
}
A1 2 3
B1 3 2
C3 2 1
D2 3 1
Attempts:
2 left
💡 Hint
Count how many nodes are in the queue at each level before processing them.
🧠 Conceptual
expert
2:00remaining
Why Use a Queue in Level Order Traversal (BFS)?
Which of the following best explains why a queue is used in level order traversal of a binary tree?
AA queue ensures nodes are processed in the order they are discovered, maintaining the correct level order.
BA queue allows random access to nodes, speeding up traversal.
CA queue automatically balances the tree during traversal.
DA queue stores nodes in sorted order by their values.
Attempts:
2 left
💡 Hint
Think about how nodes are visited level by level from left to right.

Practice

(1/5)
1. What does Level Order Traversal (BFS) of a binary tree do?
easy
A. Visits nodes in random order
B. Visits nodes in left subtree, then root, then right subtree
C. Visits nodes level by level from top to bottom, left to right
D. Visits nodes in right subtree, then root, then left subtree

Solution

  1. Step 1: Understand Level Order Traversal

    Level order traversal visits nodes level by level starting from the root, moving left to right at each level.
  2. Step 2: Compare with other traversals

    Other traversals like inorder or postorder do not visit nodes level-wise but follow subtree orders.
  3. Final Answer:

    Visits nodes level by level from top to bottom, left to right -> Option C
  4. Quick Check:

    Level Order = BFS = top-down, left-right [OK]
Hint: Level order means visit nodes by levels, left to right [OK]
Common Mistakes:
  • Confusing level order with inorder or preorder traversal
  • Thinking traversal is random
  • Mixing left and right subtree orders
2. Which Java code snippet correctly initializes a queue for level order traversal of a binary tree?
easy
A. Queue<TreeNode> queue = new ArrayList<>();
B. Queue<TreeNode> queue = new LinkedList<>();
C. List<TreeNode> queue = new LinkedList<>();
D. Stack<TreeNode> queue = new Stack<>();

Solution

  1. Step 1: Identify correct queue initialization

    Java's Queue interface is implemented by LinkedList, so Queue<TreeNode> queue = new LinkedList<>() is correct.
  2. Step 2: Check other options

    ArrayList does not implement Queue, List is not a Queue, and Stack is LIFO, not FIFO needed for BFS.
  3. Final Answer:

    Queue<TreeNode> queue = new LinkedList<>(); -> Option B
  4. Quick Check:

    Queue for BFS = LinkedList implementation [OK]
Hint: Use LinkedList to implement Queue for BFS in Java [OK]
Common Mistakes:
  • Using ArrayList instead of Queue
  • Using Stack which is LIFO, not FIFO
  • Declaring List instead of Queue
3. What is the output of the following Java code performing level order traversal on this tree?
    1
   / \
  2   3
 / \
4   5

// Code snippet:
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
  TreeNode node = queue.poll();
  System.out.print(node.val + " ");
  if (node.left != null) queue.add(node.left);
  if (node.right != null) queue.add(node.right);
}
medium
A. 1 2 3 4 5
B. 1 3 2 5 4
C. 4 5 2 3 1
D. 2 4 5 1 3

Solution

  1. Step 1: Trace the queue operations

    Start with root (1). Print 1, add children 2 and 3. Then print 2, add 4 and 5. Then print 3 (no children). Then print 4 and 5.
  2. Step 2: Write output sequence

    Output is: 1 2 3 4 5
  3. Final Answer:

    1 2 3 4 5 -> Option A
  4. Quick Check:

    Level order output = 1 2 3 4 5 [OK]
Hint: Print nodes as you dequeue in BFS order [OK]
Common Mistakes:
  • Mixing preorder or inorder output with level order
  • Adding children in wrong order
  • Printing before adding children
4. Identify the bug in this Java code snippet for level order traversal:
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
  TreeNode node = queue.peek();
  System.out.print(node.val + " ");
  if (node.left != null) queue.add(node.left);
  if (node.right != null) queue.add(node.right);
}
medium
A. Using peek() instead of poll() causes infinite loop
B. Not checking if root is null
C. Adding children after printing node value
D. Queue should be Stack for BFS

Solution

  1. Step 1: Understand peek() vs poll()

    peek() returns the front element but does not remove it, so the queue never empties.
  2. Step 2: Effect on loop

    Since queue is never emptied, while loop runs infinitely printing the same node repeatedly.
  3. Final Answer:

    Using peek() instead of poll() causes infinite loop -> Option A
  4. Quick Check:

    poll() removes front, peek() does not [OK]
Hint: Use poll() to remove nodes, not peek() [OK]
Common Mistakes:
  • Confusing peek() and poll()
  • Ignoring null root check
  • Using Stack instead of Queue
5. Given a binary tree, how can you modify level order traversal to print nodes level by level on separate lines in Java?
hard
A. Print nodes as they are dequeued without tracking levels
B. Use recursion to print nodes in preorder with newlines
C. Use a stack to reverse the order and print levels bottom-up
D. Use a queue and track the number of nodes at each level, printing a newline after each level

Solution

  1. Step 1: Track nodes per level using queue size

    At each iteration, get the current queue size which equals nodes at that level. Process exactly that many nodes, then print newline.
  2. Step 2: Print nodes level-wise

    This ensures nodes of one level print on one line, then move to next line for next level.
  3. Final Answer:

    Use a queue and track the number of nodes at each level, printing a newline after each level -> Option D
  4. Quick Check:

    Queue size = nodes per level for line breaks [OK]
Hint: Use queue size to separate levels during BFS [OK]
Common Mistakes:
  • Using recursion which is not level order
  • Using stack which reverses order
  • Not tracking level size, so no line breaks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard