Skip to content
Preptima
mediumCodingEntryMidSenior

Find the lowest common ancestor of two nodes in a binary tree.

5 min readUpdated 2026-08-15

Answer

Short answer

Recurse post-order and return the node whose left and right subtrees each report back one target; if only one side reports back, propagate that result upwards. This is O(n) time and O(h) stack.

Was this answer helpful?

Likely follow-ups

  • How would you return null when one of the two nodes is absent from the tree?
  • What changes if values can repeat and you are given values rather than node references?
  • With parent pointers, can you find the LCA in O(1) extra space?
  • How would you answer many LCA queries on a static tree efficiently?

Related questions

Related Topics