Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Level-order traversal of a binary tree using a queue.

FresherFundamentalsData Structures & Algorithms
Model answer

Level-order traversal

For Level-order traversal of a binary tree using a queue., interviewers listen for a crisp definition, how the pieces interact in a real system, and one trade-off or failure mode you have seen or would guard against.

java
void levelOrder(TreeNode root) {
  if (root == null) return;
  Queue<TreeNode> q = new ArrayDeque<>();
  q.add(root);
  while (!q.isEmpty()) {
    TreeNode node = q.remove();
    visit(node);
    if (node.left != null) q.add(node.left);
    if (node.right != null) q.add(node.right);
  }
}
Process level-by-level by tracking queue size each iteration.