Maximum Width of Binary Tree in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find the maximum width of a binary tree changes as the tree grows.
The question is: how does the work increase when the tree has more nodes?
Analyze the time complexity of the following code snippet.
function widthOfBinaryTree(root) {
if (!root) return 0;
let maxWidth = 0;
let queue = [[root, 0]]; // node with index
while (queue.length) {
const length = queue.length;
const start = queue[0][1];
let end = start;
for (let i = 0; i < length; i++) {
const [node, index] = queue.shift();
end = index;
if (node.left) queue.push([node.left, 2 * index + 1]);
if (node.right) queue.push([node.right, 2 * index + 2]);
}
maxWidth = Math.max(maxWidth, end - start + 1);
}
return maxWidth;
}
This code finds the maximum width of a binary tree by level-order traversal, tracking node positions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop processes each node once, and the inner for loop visits all nodes at the current level.
- How many times: Each node is visited exactly once, so total operations grow with the number of nodes.
As the number of nodes (n) increases, the code visits each node once, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The operations increase linearly as the tree size grows.
Time Complexity: O(n)
This means the time to find the maximum width grows in direct proportion to the number of nodes in the tree.
[X] Wrong: "The time depends on the tree height only because we process level by level."
[OK] Correct: Even though we go level by level, every node is visited once, so total time depends on total nodes, not just height.
Understanding how to analyze traversal algorithms like this helps you explain your approach clearly and shows you grasp how data size affects performance.
"What if we used a depth-first search instead of breadth-first search? How would the time complexity change?"
Practice
Solution
Step 1: Understand the term 'width' in a binary tree
The width refers to how many nodes exist at the same depth or level in the tree.Step 2: Identify what 'maximum width' means
It is the largest count of nodes found at any one level across the entire tree.Final Answer:
The largest number of nodes present at any single level of the tree -> Option CQuick Check:
Maximum width = max nodes at any level [OK]
- Confusing width with height of the tree
- Thinking width is total nodes in the tree
- Mixing width with sum of node values
Solution
Step 1: Identify the correct data structure for BFS traversal
To calculate maximum width, we use level order traversal which requires a queue (FIFO).Step 2: Check JavaScript syntax for queue initialization
An array can be used as a queue with push and shift methods, so const queue = [] is correct.Final Answer:
const queue = []; -> Option BQuick Check:
Queue for BFS = array [] [OK]
- Using Set which is unordered
- Using object {} which is not a queue
- Assigning null instead of a data structure
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
const root = new TreeNode(1,
new TreeNode(2, new TreeNode(4), new TreeNode(5)),
new TreeNode(3, null, new TreeNode(7))
);
function widthOfBinaryTree(root) {
if (!root) return 0;
let maxWidth = 0;
const queue = [[root, 0]]; // node with index
while (queue.length) {
const levelLength = queue.length;
const levelIndices = [];
for (let i = 0; i < levelLength; i++) {
const [node, index] = queue.shift();
levelIndices.push(index);
if (node.left) queue.push([node.left, 2 * index]);
if (node.right) queue.push([node.right, 2 * index + 1]);
}
maxWidth = Math.max(maxWidth, levelIndices[levelIndices.length - 1] - levelIndices[0] + 1);
}
return maxWidth;
}
console.log(widthOfBinaryTree(root));Solution
Step 1: Analyze the tree structure and node indices
Level 0: Node 1 at index 0 (width 1) Level 1: Nodes 2 (index 0), 3 (index 1) width = 2 Level 2: Nodes 4 (0), 5 (1), null, 7 (3) width = 3 - 0 + 1 = 4Step 2: Calculate maximum width from indices
The widest level is level 2 with width 4, so maxWidth = 4.Final Answer:
4 -> Option AQuick Check:
Max width = 4 nodes at level 2 [OK]
- Ignoring null gaps in indexing
- Counting nodes instead of width using indices
- Confusing index calculation for children
function maxWidth(root) {
if (!root) return 0;
let maxWidth = 0;
const queue = [root];
while (queue.length) {
const levelLength = queue.length;
maxWidth = Math.max(maxWidth, levelLength);
for (let i = 0; i < levelLength; i++) {
const node = queue.shift();
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return maxWidth;
}Solution
Step 1: Understand how width is calculated here
This code counts nodes at each level but ignores gaps caused by missing nodes (nulls).Step 2: Identify why ignoring nulls causes wrong width
Width should count positions including nulls between nodes, but this code only counts existing nodes, underestimating width.Final Answer:
It does not consider null nodes between children, so width may be underestimated -> Option DQuick Check:
Missing nulls causes wrong width [OK]
- Thinking shift() is invalid in JS arrays
- Ignoring null gaps in width calculation
- Misunderstanding queue initialization
Solution
Step 1: Consider the problem of deep and sparse trees
Deep sparse trees have missing nodes causing gaps; simple node counts per level won't work.Step 2: Choose method that tracks node positions
Level order traversal with indices tracks exact positions, including gaps, allowing correct width calculation.Step 3: Evaluate other options
DFS without indices can't track gaps; recursion counting nodes/height is inaccurate; stack with node values doesn't help width.Final Answer:
Use level order traversal with node indices to track positions and calculate width -> Option AQuick Check:
Index tracking + BFS = correct max width [OK]
- Using DFS without position tracking
- Assuming total nodes/height gives width
- Using node values instead of positions
Ready to prove it?
Pass the test and this pattern moves unknown
