Skip to the solution
MediumDSA13 min read

How do you find the lowest common ancestor in a binary tree?

1.1k views

The problem

Question presented to candidate: "Given the root of a binary tree โ€” not necessarily a binary search tree โ€” and two nodes p and q that are in the tree, write a Python function that returns their lowest common ancestor: the deepest node that has both p and q as descendants, where a node counts as a descendant of itself."

What a strong answer should cover:

  • The definition, including that p can be the answer when it is an ancestor of q.
  • The recursive post-order search: return the node if it is null, p or q; if both children return non-null, the current node is the LCA.
  • O(n) time and O(h) space, and why the early return is safe only when both nodes exist.
  • How to handle a possibly missing node (count matches, no early return) and the parent-map alternative.
  • Python details: compare nodes with is (identity), nodes hash by identity so they work as dict keys, and the 1000-frame recursion limit on deep trees.
  • The BST shortcut and why it does not apply to a general binary tree.

Clarifying questions expected:

  • Is it a BST or a general binary tree?
  • Are both nodes guaranteed to be in the tree, and are they given as nodes or as values?

Code / implementation expected: Yes โ€” lca(root, p, q) returning a node, in Python 3.

  • trees
  • lca

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRecursive LCA: six queries on one tree
PythonParent map cross-check and the missing-node trap

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 42 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the k closest points to the origin?

Continue