Skip to main content
All Questions

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

Medium

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

The lowest common ancestor is defined between two nodes p and q as the lowest node in the tree that has both p and q as descendants (where we allow a node to be a descendant of itself).

Example

Consider the following binary tree:

Tree: 10 / \ 5 15 / \ \ 3 7 20 / \ / 1 8 17
  • The lowest common ancestor of nodes 5 and 15 is node 10.
  • The lowest common ancestor of nodes 3 and 7 is node 5.

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Science Interview Prep

Land your dream data science role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more.