PPractick

DSA interview question

Lowest Common Ancestor in a Binary Tree

Hard · Data structures · Topics: tree, dfs, recursion

The problem

A company org chart is a binary tree, and HR needs the lowest-ranking manager that both of two employees report up to: their lowest common ancestor (LCA), where a node can be an ancestor of itself. In a plain binary tree there's no ordering to steer the search, so do one post-order DFS. Each call returns p or q if it finds one in its subtree (or the LCA if it finds both). The first node where p and q come back from different sides is the answer.

Example: tree [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 1 → 3; p = 5, q = 4 → 5.

Function signature

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q);  // p and q exist in the tree

Test cases

Input (tree, p, q)OutputExplanation
([3,5,1,6,2,0,8,null,null,7,4], 5, 1)3On opposite sides of the root
([3,5,1,6,2,0,8,null,null,7,4], 5, 4)5A node is its own ancestor
([3,5,1,6,2,0,8,null,null,7,4], 6, 4)5
([3,5,1,6,2,0,8,null,null,7,4], 7, 8)3
([1, 2], 1, 2)1

(Confirm: values are unique; both p and q are in the tree; a node may be its own ancestor.)

How interviewers phrase it

Clarifying questions to ask

  1. Are both nodes guaranteed to be in the tree? (Yes. Otherwise, count how many were actually found.)
  2. Can a node be its own ancestor? (Yes.)
  3. Is it a BST? (No. For a BST, walk down using values.)

Follow-ups to expect

  1. "Why can the function return early when it finds p or q?"
  2. "How do you know the LCA was found?"
  3. "Alternative with parent pointers?"
  4. "Many queries?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in