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?"
Practice
Solution
Step 1: Understand Level Order Traversal
Level order traversal visits nodes starting from the root, then all nodes at the next level, and so on, moving left to right within each level.Step 2: Compare options with definition
Visits nodes level by level from top to bottom, left to right matches this definition exactly, while others describe different traversals or incorrect behavior.Final Answer:
Visits nodes level by level from top to bottom, left to right -> Option CQuick Check:
Level Order = Top to bottom, left to right [OK]
- Confusing level order with inorder or preorder traversal
- Thinking BFS visits nodes randomly
- Mixing left and right subtree orders
Solution
Step 1: Identify data structure for BFS queue
BFS uses a queue to hold nodes to visit. In JavaScript, an array can be used as a queue with push and shift methods.Step 2: Check options for correct queue initialization
const queue = [] initializes an empty array, suitable for queue operations. Others are incorrect types for queue usage.Final Answer:
const queue = [] -> Option DQuick Check:
Queue = array for BFS [OK]
- Using object {} instead of array for queue
- Initializing queue as null or number
- Not knowing how to enqueue/dequeue in JS
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
const 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);
function levelOrder(root) {
const result = [];
const queue = [root];
while (queue.length) {
const node = queue.shift();
result.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return result;
}
console.log(levelOrder(root));Solution
Step 1: Trace the BFS traversal on the tree
Start with root (1), then enqueue left (2) and right (3). Next dequeue 2, enqueue its children 4 and 5. Then dequeue 3 (no children). Then dequeue 4 and 5.Step 2: Collect visited nodes in order
Visited order is 1, 2, 3, 4, 5 as nodes are processed level by level, left to right.Final Answer:
[1, 2, 3, 4, 5] -> Option AQuick Check:
Level order output = [1, 2, 3, 4, 5] [OK]
- Mixing preorder or inorder output with BFS
- Forgetting to enqueue children in correct order
- Confusing shift() with pop() in queue
function bfs(root) {
const queue = [];
queue.push(root);
while (queue.length > 0) {
const node = queue.pop();
console.log(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}Solution
Step 1: Identify queue operation used
The code uses pop() to remove nodes from the queue, which removes from the end (stack behavior).Step 2: Understand BFS queue behavior
BFS requires removing nodes from the front (shift()), not the end. Using pop() reverses order, causing DFS-like traversal.Final Answer:
Using pop() instead of shift() causes wrong traversal order -> Option BQuick Check:
BFS needs shift(), not pop() [OK]
- Confusing pop() with shift() in queue
- Ignoring null root check (less critical here)
- Expecting return instead of console.log (not error)
Example tree:
1 / \ 2 3 / \ 4 5
Solution
Step 1: Understand grouping nodes by level
To return nodes level by level, we must know how many nodes are at each level during traversal.Step 2: Use queue size to separate levels
At each iteration, record queue length (nodes at current level), dequeue exactly that many nodes, collect their values, then enqueue their children for next level.Step 3: Compare options
Use a queue and track the number of nodes at each level to group values describes this approach correctly. Others describe preorder recursion, stack reversal, or incorrect traversal orders.Final Answer:
Use a queue and track the number of nodes at each level to group values -> Option AQuick Check:
Queue + level size tracking = nested level arrays [OK]
- Trying to use recursion without level info
- Using stack which reverses order incorrectly
- Not grouping nodes, returning flat list instead
Ready to prove it?
Pass the test and this pattern moves unknown
