Bird
Raised Fist0

Identify the subtle bug in the following code snippet for checking if a binary tree is symmetric: ```python def isMirror(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False if t1.val != t2.val: return False return isMirror(t1.left, t2.left) and isMirror(t1.right, t2.right) ```

medium🐞 Bug Identification Q7 of Q15
Tree: Depth-First Search - Symmetric Tree (DFS Approach)
Identify the subtle bug in the following code snippet for checking if a binary tree is symmetric: ```python def isMirror(t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False if t1.val != t2.val: return False return isMirror(t1.left, t2.left) and isMirror(t1.right, t2.right) ```
AThe function does not handle empty trees.
BThe recursive calls compare left subtree with left subtree instead of mirrored right subtree.
CThe value comparison is missing before recursion.
DThe base case incorrectly returns True when one node is None and the other is not.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze recursive calls

    The function compares t1.left with t2.left and t1.right with t2.right, which checks for identical structure, not mirror symmetry.
  2. Step 2: Identify correct mirrored comparison

    It should compare t1.left with t2.right and t1.right with t2.left to check mirror symmetry.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Incorrect subtree pairing breaks mirror check [OK]
Quick Trick: Mirror check requires cross subtree comparison [OK]
Common Mistakes:
MISTAKES
  • Comparing left with left subtree
  • Ignoring mirrored structure
Trap Explanation:
PITFALL
  • Candidates often write symmetric checks as identical subtree checks, missing mirror logic.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to spot subtle logic bugs in recursion
Master "Symmetric Tree (DFS Approach)" 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