📖 Scenario: You are working on a program that analyzes the shape of a binary tree. The width of a binary tree at a certain level is the number of nodes between the leftmost and rightmost non-null nodes at that level, including null nodes in between. Your task is to find the maximum width among all levels of the tree.
🎯 Goal: Build a TypeScript program that calculates the maximum width of a given binary tree using level order traversal and indexing nodes to account for null gaps.
📋 What You'll Learn
Create a binary tree node class called TreeNode with val, left, and right properties
Create a sample binary tree with the exact structure specified
Create a variable called maxWidth initialized to 0
Use a queue to perform level order traversal with node indices
Calculate the width at each level and update maxWidth
Print the final maxWidth value
💡 Why This Matters
🌍 Real World
Calculating the maximum width of a binary tree is useful in scenarios like network topology analysis, organizational charts, and understanding data structures in memory.
💼 Career
This concept is important for software engineers working with tree data structures, optimizing algorithms, and preparing for technical interviews.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a class called TreeNode with a constructor that takes a number val and initializes left and right to null. Then create the following binary tree by creating nodes and linking them:
Root node with value 1 Root's left child with value 3 Root's right child with value 2 Node 3's left child with value 5 Node 3's right child with value 3 Node 2's right child with value 9
DSA Typescript
Hint
Start by defining the TreeNode class with val, left, and right. Then create the nodes exactly as described and link them to form the tree.
2
Initialize Maximum Width Variable
Create a variable called maxWidth and set it to 0. This will keep track of the maximum width found so far.
DSA Typescript
Hint
Just create a variable maxWidth and set it to zero to start counting the maximum width.
3
Calculate Maximum Width Using Level Order Traversal
Use a queue to perform level order traversal of the tree. Store pairs of node and its index starting with root and index 0. For each level, find the width by subtracting the first index from the last index and adding 1. Update maxWidth if the current width is larger. Add children to the queue with their corresponding indices (2 * index for left child, 2 * index + 1 for right child).
DSA Typescript
Hint
Use a queue to keep track of nodes and their indices. For each level, calculate the width and update maxWidth. Add children with updated indices to the queue.
4
Print the Maximum Width
Write a console.log statement to print the value of maxWidth.
DSA Typescript
Hint
Use console.log(maxWidth) to display the maximum width after the traversal.
Practice
(1/5)
1. What does the "maximum width" of a binary tree represent?
easy
A. The largest number of nodes present at any single level of the tree
B. The height of the tree from root to the deepest leaf
C. The total number of nodes in the tree
D. The sum of values of all nodes at the widest level
Solution
Step 1: Understand the definition of width in a binary tree
The width is the count of nodes at a particular level in the tree.
Step 2: Identify maximum width
The maximum width is the largest such count among all levels.
Final Answer:
The largest number of nodes present at any single level of the tree -> Option A
Quick Check:
Maximum width = max nodes at any level [OK]
Hint: Width means count of nodes at one level, not height or sum [OK]
Common Mistakes:
Confusing width with height of the tree
Thinking width is total nodes in the tree
Assuming width is sum of node values
2. Which TypeScript data structure is best suited to track nodes level by level when finding maximum width of a binary tree?
easy
A. Queue
B. Stack
C. Set
D. Map
Solution
Step 1: Identify traversal method for levels
Level order traversal visits nodes level by level, which uses a queue.
Step 2: Choose data structure for level order
A queue allows FIFO order, perfect for processing nodes in each level sequentially.
Final Answer:
Queue -> Option A
Quick Check:
Level order traversal uses queue [OK]
Hint: Use queue for level-by-level traversal [OK]
Common Mistakes:
Using stack which is LIFO, not suitable for level order
Using set which doesn't maintain order
Using map which is key-value, not for traversal order
3. What will be the output of the following TypeScript code snippet that calculates maximum width of a binary tree?
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val: number) {
this.val = val;
this.left = null;
this.right = null;
}
}
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.right.right = new TreeNode(5);
function maxWidth(root: TreeNode | null): number {
if (!root) return 0;
const queue: Array<TreeNode> = [root];
let maxWidth = 0;
while (queue.length > 0) {
const levelSize = queue.length;
maxWidth = Math.max(maxWidth, levelSize);
for (let i = 0; i < levelSize; i++) {
const node = queue.shift()!;
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return maxWidth;
}
console.log(maxWidth(root));
Code tracks queue length per level and updates maxWidth.
Max width found is 2 at levels 2 and 3.
Final Answer:
2 -> Option B
Quick Check:
Max width = 2 nodes at widest level [OK]
Hint: Count nodes per level, track max count [OK]
Common Mistakes:
Counting total nodes instead of per level
Assuming width is height of tree
Ignoring null children in width calculation
4. The following TypeScript function aims to find the maximum width of a binary tree but has a bug. What is the bug?
function maxWidth(root: TreeNode | null): number {
if (!root) return 0;
const queue: Array<TreeNode> = [root];
let maxWidth = 0;
while (queue.length > 0) {
const levelSize = queue.length;
maxWidth = Math.max(maxWidth, levelSize);
for (let i = 0; i <= levelSize; i++) {
const node = queue.shift()!;
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
return maxWidth;
}
medium
A. The maxWidth should be updated after the for loop
B. The queue should be a stack for correct traversal
C. The for loop condition should be i < levelSize, not i <= levelSize
D. The function should return queue.length instead of maxWidth
Solution
Step 1: Examine the for loop condition
The loop runs from i = 0 to i <= levelSize, which means it runs levelSize + 1 times.
Step 2: Identify impact of off-by-one error
Calling queue.shift() one extra time causes undefined or error because queue is empty after levelSize removals.
Final Answer:
The for loop condition should be i < levelSize, not i <= levelSize -> Option C
Quick Check:
Loop runs exactly levelSize times [OK]
Hint: Use i < levelSize for loops over fixed-size levels [OK]
Common Mistakes:
Using <= instead of < in loops causing extra iteration
Confusing queue with stack for level order
Updating maxWidth inside loop incorrectly
5. Given a binary tree where some nodes are missing (null), how can you modify the maximum width calculation to include the 'null' positions between nodes, so the width counts the distance between the leftmost and rightmost non-null nodes at each level?
Choose the best approach to solve this problem in TypeScript.
hard
A. Count only non-null nodes per level ignoring positions
B. Calculate width by summing values of nodes at each level
C. Use a stack instead of a queue to track nodes
D. Assign an index to each node as if the tree was a complete binary tree, then calculate width as rightmost index - leftmost index + 1 per level
Solution
Step 1: Understand the problem with missing nodes
Simply counting nodes misses gaps caused by nulls, so width must consider positions.
Step 2: Use indexing like a complete binary tree
Assign indices to nodes: root = 0, left child = 2*index, right child = 2*index + 1.
Track min and max indices per level to find width including gaps.
Final Answer:
Assign an index to each node as if the tree was a complete binary tree, then calculate width as rightmost index - leftmost index + 1 per level -> Option D
Quick Check:
Index nodes to include null gaps [OK]
Hint: Use complete tree indexing to count gaps [OK]
Common Mistakes:
Ignoring null gaps and counting only nodes
Using stack which breaks level order
Summing node values instead of counting width
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.