Bird
Raised Fist0

Consider the following buggy code for inverting a binary tree. Which line contains the subtle bug that causes incorrect inversion?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Invert Binary Tree
Consider the following buggy code for inverting a binary tree. Which line contains the subtle bug that causes incorrect inversion?
ALine 3: Swapping children before recursive calls
BLine 5: Recursive call on right child
CLine 4: Recursive call on left child
DLine 2: Missing check for empty tree
Step-by-Step Solution
  1. Step 1: Analyze order of operations

    The code swaps children before recursively inverting subtrees, which means subtrees are swapped but not inverted themselves.
  2. Step 2: Identify why swapping before recursion is incorrect

    Swapping first causes recursion to invert the wrong subtrees, leading to partial or incorrect inversion.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Swapping must happen after recursive calls to invert subtrees correctly [OK]
Quick Trick: Swap after recursion, not before, to invert subtrees properly [OK]
Common Mistakes:
MISTAKES
  • Swapping children before recursion
  • Ignoring null root checks
  • Confusing left and right subtree recursion order
Trap Explanation:
PITFALL
  • Swapping before recursion looks plausible but breaks subtree inversion correctness.
Interviewer Note:
CONTEXT
  • Checks if candidate understands correct recursion and swap order.
Master "Invert 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