Bird
Raised Fist0

Given the tree below and nodes p=5 and q=1, what is the final returned node's value?

easy🧾 Code Trace Q12 of Q15
Tree: Depth-First Search - Lowest Common Ancestor of Binary Tree
Consider the following code snippet implementing the parent pointer + ancestor set approach for Lowest Common Ancestor. Given the tree below and nodes p=5 and q=1, what is the final returned node's value? Tree structure: 3 / \ 5 1 / \ \ 6 2 8
def lowestCommonAncestor(root, p, q):
    parent = {root: None}
    stack = [root]
    while p not in parent or q not in parent:
        node = stack.pop()
        if node.left:
            parent[node.left] = node
            stack.append(node.left)
        if node.right:
            parent[node.right] = node
            stack.append(node.right)

    ancestors = set()
    while p:
        ancestors.add(p)
        p = parent[p]
    while q not in ancestors:
        q = parent[q]
    return q
A3
B5
C1
D2
Step-by-Step Solution
Solution:
  1. Step 1: Trace parent map construction

    Stack starts with root=3. Pop 3, add children 5 and 1 with parent 3. Pop 1, add child 8 with parent 1. Pop 8 (no children). Pop 5, add children 6 and 2 with parent 5. Parent map built for all nodes.
  2. Step 2: Trace ancestor sets and final return

    Ancestors of p=5 are {5,3,None}. For q=1, check if in ancestors: 1 not in {5,3}, move to parent 3 which is in ancestors. Return 3.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Root 3 is LCA of 5 and 1 in given tree [OK]
Quick Trick: LCA of sibling subtrees is their parent [OK]
Common Mistakes:
MISTAKES
  • Returning p or q directly
  • Confusing parent pointers
  • Off-by-one in ancestor check
Trap Explanation:
PITFALL
  • Candidates often confuse which node is returned when one node is ancestor of the other.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute DFS and parent pointer logic.
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