Bird
Raised Fist0

Consider the following buggy code for checking if a binary tree is symmetric. Which line contains the subtle bug that causes incorrect results for asymmetric trees?

medium🐞 Bug Identification Q14 of Q15
Tree: Depth-First Search - Symmetric Tree (DFS Approach)
Consider the following buggy code for checking if a binary tree is symmetric. Which line contains the subtle bug that causes incorrect results for asymmetric trees?
def isSymmetric(root: Optional[TreeNode]) -> bool:
    def isMirror(t1: Optional[TreeNode], t2: Optional[TreeNode]) -> bool:
        if not t1 or not t2:
            return True
        if t1.val != t2.val:
            return False
        return isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left)

    return isMirror(root.left, root.right) if root else True
ALine 5: if t1.val != t2.val: return False
BLine 3: if not t1 or not t2: return True
CLine 6: return isMirror(t1.left, t2.right) and isMirror(t1.right, t2.left)
DLine 8: return isMirror(root.left, root.right) if root else True
Step-by-Step Solution
Solution:
  1. Step 1: Analyze base case for null nodes

    The line returns true if either t1 or t2 is null, but it should only return true if both are null.
  2. Step 2: Identify that returning true when only one node is null causes false positives

    This causes asymmetric trees with missing nodes on one side to be incorrectly considered symmetric.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Base case must check both nodes null equality, not just one [OK]
Quick Trick: Base case must return true only if both nodes are null [OK]
Common Mistakes:
MISTAKES
  • Returning true if only one node is null
  • Forgetting to check node values before recursion
  • Mixing left and right subtree comparisons
Trap Explanation:
PITFALL
  • Returning true on single null node looks plausible but breaks correctness on asymmetric trees.
Interviewer Note:
CONTEXT
  • Tests attention to base case correctness in recursive tree problems.
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