Tree Traversal Level Order BFS in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to visit all nodes in a tree grows as the tree gets bigger.
How does the number of steps change when the tree has more nodes?
Analyze the time complexity of the following code snippet.
function levelOrderBFS(root) {
if (!root) return [];
const queue = [root];
const result = [];
while (queue.length > 0) {
const node = queue.shift();
result.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return result;
}
This code visits every node in a binary tree level by level, from left to right.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop that removes nodes from the queue and adds their children.
- How many times: Once for each node in the tree, because each node is added and removed exactly once.
As the number of nodes grows, the steps to visit them all grow in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits and queue operations |
| 100 | About 100 visits and queue operations |
| 1000 | About 1000 visits and queue operations |
Pattern observation: The number of steps grows directly with the number of nodes.
Time Complexity: O(n)
This means the time to complete grows linearly with the number of nodes in the tree.
[X] Wrong: "Because of the nested if statements, the time complexity is more than linear."
[OK] Correct: Each node is still visited only once, and the if checks are simple conditions, so they do not multiply the total steps.
Understanding level order traversal helps you work with trees in many real problems, showing you can handle data step-by-step in a clear order.
"What if we used a recursive approach instead of a queue? How would the time complexity change?"