Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Maximum Width of Binary Tree in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Maximum Width Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Maximum Width Calculation
What is the output of the following code that calculates the maximum width of a binary tree?
DSA Javascript
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function widthOfBinaryTree(root) {
  if (!root) return 0;
  let maxWidth = 0;
  let queue = [[root, 0]]; // node and index

  while (queue.length > 0) {
    const levelLength = queue.length;
    const levelIndices = queue.map(pair => pair[1]);
    const minIndex = levelIndices[0];
    const maxIndex = levelIndices[levelIndices.length - 1];
    maxWidth = Math.max(maxWidth, maxIndex - minIndex + 1);

    for (let i = 0; i < levelLength; i++) {
      const [node, index] = queue.shift();
      if (node.left) queue.push([node.left, 2 * (index - minIndex)]);
      if (node.right) queue.push([node.right, 2 * (index - minIndex) + 1]);
    }
  }
  return maxWidth;
}

// Tree structure:
//       1
//      / \
//     3   2
//    /     \
//   5       9
//  /         \
// 6           7

const root = new TreeNode(1,
  new TreeNode(3,
    new TreeNode(5,
      new TreeNode(6)
    )
  ),
  new TreeNode(2,
    null,
    new TreeNode(9,
      null,
      new TreeNode(7)
    )
  )
);

console.log(widthOfBinaryTree(root));
A4
B8
C5
D6
Attempts:
2 left
💡 Hint
Consider how the indices are assigned to nodes and how the width is calculated as the difference between max and min indices at each level.
❓ Predict Output
intermediate
2:00remaining
Maximum Width for a Skewed Tree
What is the output of the code below for a skewed binary tree (all nodes only have a right child)?
DSA Javascript
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function widthOfBinaryTree(root) {
  if (!root) return 0;
  let maxWidth = 0;
  let queue = [[root, 0]];

  while (queue.length > 0) {
    const levelLength = queue.length;
    const levelIndices = queue.map(pair => pair[1]);
    const minIndex = levelIndices[0];
    const maxIndex = levelIndices[levelIndices.length - 1];
    maxWidth = Math.max(maxWidth, maxIndex - minIndex + 1);

    for (let i = 0; i < levelLength; i++) {
      const [node, index] = queue.shift();
      if (node.left) queue.push([node.left, 2 * (index - minIndex)]);
      if (node.right) queue.push([node.right, 2 * (index - minIndex) + 1]);
    }
  }
  return maxWidth;
}

// Tree structure:
// 1 -> 2 -> 3 -> 4 (all right children)
const root = new TreeNode(1,
  null,
  new TreeNode(2,
    null,
    new TreeNode(3,
      null,
      new TreeNode(4)
    )
  )
);

console.log(widthOfBinaryTree(root));
A3
B2
C4
D1
Attempts:
2 left
💡 Hint
In a skewed tree, the width at each level is usually 1 because there is only one node per level.
🔧 Debug
advanced
2:00remaining
Identify the Error in Width Calculation
The following code attempts to calculate the maximum width of a binary tree but produces incorrect results. What is the main reason for the error?
DSA Javascript
function widthOfBinaryTree(root) {
  if (!root) return 0;
  let maxWidth = 0;
  let queue = [[root, 0]];

  while (queue.length > 0) {
    const levelLength = queue.length;
    const minIndex = queue[0][1];
    const maxIndex = queue[levelLength - 1][1];
    maxWidth = Math.max(maxWidth, maxIndex - minIndex + 1);

    for (let i = 0; i < levelLength; i++) {
      const [node, index] = queue.shift();
      if (node.left) queue.push([node.left, 2 * index]);
      if (node.right) queue.push([node.right, 2 * index + 1]);
    }
  }
  return maxWidth;
}
AThe maxWidth calculation should use multiplication instead of subtraction.
BThe queue is not initialized properly with root and index 1 instead of 0.
CIndices are not normalized by subtracting minIndex, causing overflow and incorrect width.
DThe function does not handle null nodes in the queue, causing runtime errors.
Attempts:
2 left
💡 Hint
Check how indices are assigned to child nodes relative to the current level's minimum index.
🧠 Conceptual
advanced
1:30remaining
Why Use Index Normalization in Maximum Width Calculation?
Why is it important to normalize indices by subtracting the minimum index at each level when calculating the maximum width of a binary tree?
ATo prevent integer overflow and keep indices small for accurate width calculation.
BTo ensure the tree is balanced before calculating width.
CTo sort the nodes at each level by their values.
DTo convert the tree into a linked list for easier traversal.
Attempts:
2 left
💡 Hint
Think about what happens to indices as the tree depth increases.
🚀 Application
expert
2:30remaining
Maximum Width of Binary Tree with Missing Nodes
Given the following binary tree, what is the maximum width calculated by the standard algorithm that uses index normalization? // Tree structure: // 1 // / \ // 2 3 // \ \ // 5 7 // / \ // 9 8
DSA Javascript
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function widthOfBinaryTree(root) {
  if (!root) return 0;
  let maxWidth = 0;
  let queue = [[root, 0]];

  while (queue.length > 0) {
    const levelLength = queue.length;
    const minIndex = queue[0][1];
    const maxIndex = queue[levelLength - 1][1];
    maxWidth = Math.max(maxWidth, maxIndex - minIndex + 1);

    for (let i = 0; i < levelLength; i++) {
      const [node, index] = queue.shift();
      if (node.left) queue.push([node.left, 2 * (index - minIndex)]);
      if (node.right) queue.push([node.right, 2 * (index - minIndex) + 1]);
    }
  }
  return maxWidth;
}

const root = new TreeNode(1,
  new TreeNode(2,
    null,
    new TreeNode(5,
      new TreeNode(9)
    )
  ),
  new TreeNode(3,
    null,
    new TreeNode(7,
      null,
      new TreeNode(8)
    )
  )
);

console.log(widthOfBinaryTree(root));
A6
B5
C8
D7
Attempts:
2 left
💡 Hint
Consider the indices assigned to nodes at the third level and how gaps affect width.

Practice

(1/5)
1. What does the "maximum width" of a binary tree represent?
easy
A. The height of the tree from root to the deepest leaf
B. The total number of nodes in the tree
C. The largest number of nodes present at any single level of the tree
D. The sum of values of all nodes at the widest level

Solution

  1. 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.
  2. Step 2: Identify what 'maximum width' means

    It is the largest count of nodes found at any one level across the entire tree.
  3. Final Answer:

    The largest number of nodes present at any single level of the tree -> Option C
  4. 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
  • Mixing width with sum of node values
2. Which of the following JavaScript code snippets correctly initializes a queue to help calculate the maximum width of a binary tree?
easy
A. const queue = {};
B. const queue = [];
C. const queue = new Set();
D. const queue = null;

Solution

  1. Step 1: Identify the correct data structure for BFS traversal

    To calculate maximum width, we use level order traversal which requires a queue (FIFO).
  2. 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.
  3. Final Answer:

    const queue = []; -> Option B
  4. Quick Check:

    Queue for BFS = array [] [OK]
Hint: Use array [] as queue for BFS in JavaScript [OK]
Common Mistakes:
  • Using Set which is unordered
  • Using object {} which is not a queue
  • Assigning null instead of a data structure
3. Consider the following JavaScript code to find the maximum width of a binary tree. What will be the output?
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));
medium
A. 4
B. 3
C. 2
D. 5

Solution

  1. 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 = 4
  2. Step 2: Calculate maximum width from indices

    The widest level is level 2 with width 4, so maxWidth = 4.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    Max width = 4 nodes at level 2 [OK]
Hint: Track node indices to find width = max index - min index + 1 [OK]
Common Mistakes:
  • Ignoring null gaps in indexing
  • Counting nodes instead of width using indices
  • Confusing index calculation for children
4. The following code attempts to compute the maximum width of a binary tree but has a bug. What is the bug?
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;
}
medium
A. It pushes nodes into queue before checking if queue is empty
B. It uses shift() which is not allowed in JavaScript arrays
C. It does not initialize maxWidth to zero
D. It does not consider null nodes between children, so width may be underestimated

Solution

  1. Step 1: Understand how width is calculated here

    This code counts nodes at each level but ignores gaps caused by missing nodes (nulls).
  2. 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.
  3. Final Answer:

    It does not consider null nodes between children, so width may be underestimated -> Option D
  4. Quick Check:

    Missing nulls causes wrong width [OK]
Hint: Include nulls in queue to track gaps for correct width [OK]
Common Mistakes:
  • Thinking shift() is invalid in JS arrays
  • Ignoring null gaps in width calculation
  • Misunderstanding queue initialization
5. You want to find the maximum width of a binary tree but the tree can be very deep and sparse. Which approach below best handles this efficiently in JavaScript?
hard
A. Use level order traversal with node indices to track positions and calculate width
B. Use depth-first traversal and count nodes at each depth without indices
C. Use recursion to count total nodes and divide by height
D. Use a stack to store nodes and calculate width by node values

Solution

  1. 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.
  2. Step 2: Choose method that tracks node positions

    Level order traversal with indices tracks exact positions, including gaps, allowing correct width calculation.
  3. 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.
  4. Final Answer:

    Use level order traversal with node indices to track positions and calculate width -> Option A
  5. Quick Check:

    Index tracking + BFS = correct max width [OK]
Hint: Track indices in BFS to handle sparse trees efficiently [OK]
Common Mistakes:
  • Using DFS without position tracking
  • Assuming total nodes/height gives width
  • Using node values instead of positions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard