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
- Given a binary tree, decide whether it is a valid binary search tree.mediumAlso on trees and binary-search-tree5 min
- A bundle can contain products or other bundles, and the pricing code should not care which it is holding. How would you model that?mediumAlso on recursion6 min
- Count the ways to place N queens on an N by N board so that no two attack each other.hardAlso on recursion5 min
- Generate every permutation of an array that may contain duplicates, then tell me how large the search tree ismediumAlso on recursion4 min