Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Maximum Width of Binary Tree in DSA Python - 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 maximum width of the following binary tree?

Tree structure:
1
/ \
2 3
/ \
4 5

Assume the width is the maximum number of nodes at any level.
DSA Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def width_of_binary_tree(root):
    if not root:
        return 0
    max_width = 0
    queue = [(root, 0)]  # (node, index)
    while queue:
        level_length = len(queue)
        _, first_index = queue[0]
        for i in range(level_length):
            node, index = queue.pop(0)
            if node.left:
                queue.append((node.left, 2 * index))
            if node.right:
                queue.append((node.right, 2 * index + 1))
        max_width = max(max_width, index - first_index + 1)
    return max_width

root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.right.right = TreeNode(5)

print(width_of_binary_tree(root))
A3
B2
C4
D5
Attempts:
2 left
💡 Hint
Count the nodes at each level and consider the positions of nodes to calculate width.
❓ Predict Output
intermediate
2:00remaining
Output of Maximum Width for Skewed Tree
What is the maximum width of this skewed binary tree?

Tree structure:
1
\
2
\
3
\
4
DSA Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def width_of_binary_tree(root):
    if not root:
        return 0
    max_width = 0
    queue = [(root, 0)]
    while queue:
        level_length = len(queue)
        _, first_index = queue[0]
        for i in range(level_length):
            node, index = queue.pop(0)
            if node.left:
                queue.append((node.left, 2 * index))
            if node.right:
                queue.append((node.right, 2 * index + 1))
        max_width = max(max_width, index - first_index + 1)
    return max_width

root = TreeNode(1)
root.right = TreeNode(2)
root.right.right = TreeNode(3)
root.right.right.right = TreeNode(4)

print(width_of_binary_tree(root))
A4
B2
C3
D1
Attempts:
2 left
💡 Hint
In a skewed tree, only one node exists at each level.
🔧 Debug
advanced
2:00remaining
Identify the Error in Width Calculation Code
What error will this code produce when calculating the maximum width of a binary tree?
DSA Python
def width_of_binary_tree(root):
    if not root:
        return 0
    max_width = 0
    queue = [(root, 0)]
    while queue:
        level_length = len(queue)
        _, first_index = queue[0]
        for i in range(level_length):
            node, index = queue.pop(0)
            if node.left:
                queue.append((node.left, index * 2 + 1))
            if node.right:
                queue.append((node.right, index * 2 + 2))
        max_width = max(max_width, index - first_index + 1)
    return max_width
AIt raises an IndexError due to empty queue access.
BIt returns incorrect width because child indices are wrongly calculated.
CIt raises a TypeError because of wrong data types in queue.
DThe code runs correctly and returns the maximum width.
Attempts:
2 left
💡 Hint
Check how child indices are assigned compared to the standard formula.
🧠 Conceptual
advanced
1:30remaining
Understanding Width Calculation in Sparse Binary Trees
Why do we use indices (like 2 * index and 2 * index + 1) when calculating the maximum width of a binary tree?
ATo uniquely identify each node's position as if the tree was complete, allowing width calculation including gaps.
BTo count the total number of nodes in the tree.
CTo calculate the height of the tree by indexing nodes.
DTo sort the nodes at each level in ascending order.
Attempts:
2 left
💡 Hint
Think about how missing nodes affect width measurement.
❓ Predict Output
expert
3:00remaining
Maximum Width of Complex Binary Tree
What is the maximum width of this binary tree?

Tree structure:
1
/ \
2 3
/ \
4 5
\ / \
6 7 8
\
9
DSA Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def width_of_binary_tree(root):
    if not root:
        return 0
    max_width = 0
    queue = [(root, 0)]
    while queue:
        level_length = len(queue)
        _, first_index = queue[0]
        for i in range(level_length):
            node, index = queue.pop(0)
            if node.left:
                queue.append((node.left, 2 * index))
            if node.right:
                queue.append((node.right, 2 * index + 1))
        max_width = max(max_width, index - first_index + 1)
    return max_width

root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.left.right = TreeNode(6)
root.right.right = TreeNode(5)
root.right.right.left = TreeNode(7)
root.right.right.right = TreeNode(8)
root.right.right.left.right = TreeNode(9)

print(width_of_binary_tree(root))
A8
B6
C7
D5
Attempts:
2 left
💡 Hint
Track the indices of nodes at the widest level carefully.

Practice

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

Solution

  1. Step 1: Understand the term "width" in binary trees

    The width of a binary tree at a level is the count of nodes present at that level.
  2. Step 2: Define maximum width

    The maximum width is the largest such count among all levels of the tree.
  3. Final Answer:

    The maximum number of nodes present at any level of the tree -> Option C
  4. Quick Check:

    Width means node count per level = maximum width [OK]
Hint: Maximum width = max nodes in any single level [OK]
Common Mistakes:
  • Confusing width with height
  • Counting total nodes instead of per level
  • Summing node values instead of counting nodes
2. Which of the following Python code snippets correctly initializes a queue to help find the maximum width of a binary tree?
easy
A. queue = [(root, 0)]
B. queue = [root]
C. queue = root
D. queue = []

Solution

  1. Step 1: Understand queue usage in width calculation

    We use a queue to hold nodes along with their position indices to track width.
  2. Step 2: Check correct initialization

    Initializing queue as a list of tuples with (node, index) is correct: [(root, 0)].
  3. Final Answer:

    queue = [(root, 0)] -> Option A
  4. Quick Check:

    Queue holds (node, index) pairs = correct initialization [OK]
Hint: Use (node, index) pairs in queue for width tracking [OK]
Common Mistakes:
  • Using queue = [root] without index
  • Assigning queue = root (not a list)
  • Starting with empty queue []
3. What is the output of the following code snippet that calculates the maximum width of a binary tree?
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def widthOfBinaryTree(root):
    if not root:
        return 0
    max_width = 0
    queue = [(root, 0)]
    while queue:
        level_length = len(queue)
        _, first_index = queue[0]
        for i in range(level_length):
            node, index = queue.pop(0)
            if node.left:
                queue.append((node.left, 2 * index))
            if node.right:
                queue.append((node.right, 2 * index + 1))
        max_width = max(max_width, index - first_index + 1)
    return max_width

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.right = Node(5)
print(widthOfBinaryTree(root))
medium
A. 3
B. 2
C. 5
D. 4

Solution

  1. Step 1: Trace the tree structure and 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 (index 0), 5 (index 3) width = 3 - 0 + 1 = 4
  2. Step 2: Calculate max width

    Maximum width is 4 at level 2.
  3. Final Answer:

    4 -> Option D
  4. Quick Check:

    Max width = 4 nodes wide at level 2 [OK]
Hint: Track indices to find width = last - first + 1 [OK]
Common Mistakes:
  • Ignoring index gaps causing wrong width
  • Using length of queue directly as width
  • Not updating max_width correctly
4. Identify the bug in this code snippet that attempts to find the maximum width of a binary tree:
def widthOfBinaryTree(root):
    if not root:
        return 0
    max_width = 0
    queue = [(root, 0)]
    while queue:
        level_length = len(queue)
        _, first_index = queue[0]
        for i in range(level_length):
            node, index = queue.pop(0)
            if node.left:
                queue.append((node.left, index * 2 + 1))
            if node.right:
                queue.append((node.right, index * 2 + 2))
        max_width = max(max_width, index - first_index + 1)
    return max_width
medium
A. Left and right child indices are swapped; should be 2*index and 2*index+1
B. Queue should be a stack for correct traversal
C. max_width update is outside the while loop
D. Missing check for empty tree at start

Solution

  1. Step 1: Check child index calculation

    Correct indices for left and right children are 2*index and 2*index+1 respectively.
  2. Step 2: Identify incorrect index formula

    Code uses index*2+1 for left and index*2+2 for right, which is swapped and incorrect.
  3. Final Answer:

    Left and right child indices are swapped; should be 2*index and 2*index+1 -> Option A
  4. Quick Check:

    Child indices must be 2*i and 2*i+1 [OK]
Hint: Left child = 2*i, right child = 2*i+1 [OK]
Common Mistakes:
  • Swapping left and right child indices
  • Using stack instead of queue
  • Updating max_width outside loop
5. Given a binary tree where some levels have missing nodes, which approach correctly calculates the maximum width including gaps between nodes?
Choose the best method to handle this scenario.
hard
A. Count only existing nodes at each level ignoring gaps
B. Use level order traversal with node indices to calculate width as last_index - first_index + 1
C. Calculate width as the maximum depth of the tree
D. Sum the values of nodes at each level and find the maximum sum

Solution

  1. Step 1: Understand gaps in tree levels

    Missing nodes create gaps, so counting nodes alone misses width.
  2. Step 2: Use indices to include gaps

    Assign indices to nodes as if tree was complete; width = last_index - first_index + 1.
  3. Step 3: Apply level order traversal with indices

    This method captures true width including empty spaces between nodes.
  4. Final Answer:

    Use level order traversal with node indices to calculate width as last_index - first_index + 1 -> Option B
  5. Quick Check:

    Index-based width includes gaps = correct max width [OK]
Hint: Use indices to count gaps for true width [OK]
Common Mistakes:
  • Ignoring gaps by counting nodes only
  • Using tree depth as width
  • Summing node values instead of counting width
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