Prepin
Log in

Determine the Lowest Common Ancestor (LCA) of two nodes within a binary tree.

Approach / Explanation

The Lowest Common Ancestor (LCA) of two nodes, n1 and n2, is the deepest node in tree T that has both n1 and n2 as descendants, allowing a node to be considered a descendant of itself. In simpler terms, this means you need to traverse a binary tree to find the lowest node from which both nodes n1 and n2 can be accessed. A binary tree is a type of data structure where each node can have at most two children, known as the left child and the right child. To tackle this problem, keep these important points in mind: The LCA might be one of the nodes themselves if n1 is a parent of n2 or vice versa. If the LCA is neither n1 nor n2, then while traversing the tree, you will encounter a point where the paths to n1 and n2 diverge, and that point will be the LCA. Start iterating through the tree from the root; if the current node during the iteration matches either n1 or n2, or if one node is located in the left subtree while the other is in the right subtree (or vice versa), then that node is the LCA.

Suggested Answer

Consider the following binary tree, which consists of nodes {1, 2, 3, 4, 5, 6, 7}, and your task is to determine the LCA of nodes 4 and 5. 1 / \ 2 3 / \ 4 5 In this scenario, you begin your traversal at the root. Upon reaching the node with the value 2, you can observe that both nodes 4 and 5 are descendants of this node. Since there is no other common ancestor of nodes 4 and 5 located at a lower level than node 2, the LCA for nodes 4 and 5 is node 2.

Alternative Answer

Imagine we have a binary tree structured like this: 3 / \ 5 1 / \ / \ 6 2 0 8 / \ 7 4 In this scenario, we are looking for the Lowest Common Ancestor (LCA) of nodes 6 and 4. Begin by traversing from the root. You will notice that nodes 5 and 1 could potentially be ancestors of both nodes 6 and 4. As you explore further, while node 1 and its descendants are not ancestors of either 6 or 4, node 5 and its left child, 6, could serve as ancestors for both 6 and 4. However, the left subtree of node 5 does not include node 4. Consequently, node 5 is determined to be the Lowest Common Ancestor of nodes 6 and 4.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.