Bird
Raised Fist0

In the following code snippet for inverting a binary tree, which line causes the inversion to fail by not correctly swapping the children?

medium🐛 Buggy Code Q7 of Q15
Tree: Depth-First Search - Invert Binary Tree
In the following code snippet for inverting a binary tree, which line causes the inversion to fail by not correctly swapping the children?
def invertTree(node):
    if not node:
        return None
    invertTree(node.left)
    invertTree(node.right)
    node.left = node.right
    node.right = node.left
    return node
ALine 7: node.right = node.left
BLine 5: invertTree(node.right)
CLine 6: node.left = node.right
DLine 4: invertTree(node.left)
Step-by-Step Solution
Solution:
  1. Step 1: Analyze swapping lines

    Lines 6 and 7 attempt to swap children but overwrite values incorrectly.
  2. Step 2: Identify bug

    Line 7 assigns node.right = node.left after node.left was set to node.right, losing original left child.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Swapping requires temporary variable [OK]
Quick Trick: Swapping without temp variable overwrites values [OK]
Common Mistakes:
MISTAKES
  • Ignoring need for temporary variable during swap
  • Assuming recursive calls fix swapping errors
Trap Explanation:
PITFALL
  • Overwriting node.right with node.left after node.left was changed loses original data.
Interviewer Note:
CONTEXT
  • Tests debugging skills and understanding of pointer swapping.
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