Bird
Raised Fist0

Examine the recursive DFS code below for finding LCA. What is the logical error that causes incorrect results when one node is ancestor of the other?

medium🐞 Bug Q7 of Q15
Tree: Depth-First Search - Lowest Common Ancestor of Binary Tree
Examine the recursive DFS code below for finding LCA. What is the logical error that causes incorrect results when one node is ancestor of the other?
def LCA(root, p, q):
    if not root:
        return None
    if root == p or root == q:
        return root
    left = LCA(root.left, p, q)
    right = LCA(root.right, p, q)
    if left and right:
        return root
    return left or right
AReturns root prematurely when root matches p or q without checking subtrees
BNo error; code correctly handles ancestor-descendant cases
CFails to check if both left and right are None before returning
DDoes not handle the case when p and q are the same node
Step-by-Step Solution
Solution:
  1. Step 1: Base case returns root if matches p or q

    This correctly identifies if current node is one of the targets.
  2. Step 2: Recursively search left and right subtrees

    Left and right calls find p or q in subtrees.
  3. Step 3: If both sides return non-null, current root is LCA

    This covers ancestor-descendant and sibling cases.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Code correctly handles ancestor-descendant [OK]
Quick Trick: Returning root on match is correct base case [OK]
Common Mistakes:
MISTAKES
  • Assuming premature return causes error
  • Overcomplicating ancestor-descendant handling
Trap Explanation:
PITFALL
  • Misreading base case as bug when it is correct
Interviewer Note:
CONTEXT
  • Tests ability to analyze correctness of standard recursive LCA code
Master "Lowest Common Ancestor of 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