Bird
Raised Fist0

Consider the following buggy deserialization code snippet for BFS-based tree reconstruction. Which line contains the subtle bug that causes incorrect tree structure when deserializing?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Serialize and Deserialize Binary Tree
Consider the following buggy deserialization code snippet for BFS-based tree reconstruction. Which line contains the subtle bug that causes incorrect tree structure when deserializing?
def deserialize(data):
    if not data:
        return None
    vals = data.split(',')
    root = TreeNode(int(vals[0]))
    queue = deque([root])
    i = 1
    while queue:
        node = queue.popleft()
        if vals[i] != 'X':
            node.left = TreeNode(int(vals[i]))
            queue.append(node.left)
        i += 1
        if vals[i] != 'X':
            node.right = TreeNode(int(vals[i]))
            queue.append(node.right)
        i += 1
    return root
ALine: if vals[i] != 'X': (left child check)
BLine: i += 1 (after left child assignment)
CLine: if vals[i] != 'X': (right child check)
DLine: while queue: (loop condition)
Step-by-Step Solution
  1. Step 1: Identify potential infinite loop

    The loop condition 'while queue:' does not check if 'i' has exceeded vals length, risking index out of range or infinite loop.
  2. Step 2: Understand impact on deserialization

    Without checking 'i < len(vals)', the loop may continue after all nodes processed, causing errors or incorrect tree structure.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Loop condition must ensure 'i' stays within bounds to avoid deserialization bugs [OK]
Quick Trick: Loop must check index bounds to avoid infinite loops [OK]
Common Mistakes:
MISTAKES
  • Not checking index bounds in deserialization loops
  • Mixing up left and right child assignments
  • Forgetting to append children to queue
Trap Explanation:
PITFALL
  • Candidates often overlook loop termination conditions related to input length, causing subtle bugs.
Interviewer Note:
CONTEXT
  • Tests attention to boundary conditions and loop invariants in deserialization code.
Master "Serialize and Deserialize Binary Tree" in Tree: Depth-First Search

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Tree: Depth-First Search Quizzes