Structure behind level-order traversal — Aptitude Question
Structure behind level-order traversal: Which data structure does a level-order (breadth-first) traversal of a… Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 45 seconds
Question
Which data structure does a level-order (breadth-first) traversal of a binary tree rely on?
Options
- A hash table
- A min-heap
- A queue
- A stack
Show the answer and the worked solution
Correct answer: C. A queue
Worked solution
- Level-order visits all nodes at depth d before any node at depth d + 1.
- Removing a node and adding its children keeps that order, because children join behind everything already waiting.
- A queue is exactly that discipline — first in, first out — whereas a stack would reverse the order and produce a depth-first walk instead.
Answer: A queue.
The idea
Breadth-first anything — tree levels, shortest paths in an unweighted graph — is a queue. Depth-first anything is a stack, whether explicit or the recursion stack.
Shortcut. Nodes must leave in the order they were discovered, level by level, which is first in, first out; a heap orders by key and a hash table has no order, so a queue.
Common trap. "A stack" is the usual tool for tree traversals through recursion, but last in, first out dives deep and produces a depth-first order.
All Data Structures & Algorithms questions · placement mock tests