Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/Find the Lowest Common Ancestor (LCA) in a Binary Tree.

Find the Lowest Common Ancestor (LCA) in a Binary Tree.

Python/Codingeasy3 min read

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

The Lowest Common Ancestor (LCA) of two nodes, p and q, in a binary tree is the lowest node that has both p and q as descendants (where a node can be a descendant of itself). The most common approach…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories

Why This Question Matters

This easy-level Python/Coding question appears frequently in data engineering interviews at companies like Flipkart. While less common, it tests deeper understanding that distinguishes strong candidates.

How to Approach This

Start by clearly defining the core concept being asked about. Interviewers want to see that you understand the fundamentals before diving into implementation details. Structure your answer with a definition, then explain the practical application with a concise example. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
522 wordsIncludes code

The Lowest Common Ancestor (LCA) of two nodes, p and q, in a binary tree is the lowest node that has both p and q as descendants (where a node can be a descendant of itself). The most common approach leverages a recursive post-order traversal.

Mechanics and Logic

The core idea is to traverse the tree, checking if the current node is p or q.

  • Base Cases: If the current root is None, return None. If root is p or q, return root (as it's the first ancestor found on the path from the root).

  • Recurse: Recursively call the function for the left and right subtrees. These calls will return p, q, or None if found in their respective subtrees.

  • Combine Results:

  • * If both the left and right recursive calls return a non-null node, it means p was found in one subtree and q in the other. Therefore, the current root is their LCA.
    * If only one of the left or right calls returns a non-null node, it implies either that node is the LCA (if the other target node is not in this subtree), or one of p or q is an ancestor of the other, and the returned node is that ancestor. In this case, return the non-null result.
    * If both left and right calls return None, neither p nor q were found in this subtree.

    This algorithm has a time complexity of O(N), as it visits each node at most once. The space complexity is O(H) due to the recursion stack, where H is the height of the tree. This pattern is useful in data lineage tools or dependency graphs (e.g., dbt models) to find common ancestors in hierarchical structures.

    Specific Cases and Optimizations

    For a Binary Search Tree (BST), the LCA can be found more efficiently. Since BSTs maintain an ordered property, you can navigate by comparing p.val and q.val with root.val. If both are smaller, go left; if both are larger, go right. If one is smaller and one is larger (or one equals root.val), then root is the LCA. This can be done iteratively, achieving O(H) time complexity.

    It's important to handle edge cases like p or q not existing in the tree (the algorithm would return None or the existing node if only one is found) and when p equals q (the algorithm correctly returns p as its own ancestor).

    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    

    def lowestCommonAncestor(root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
    if not root or root == p or root == q:
    return root

    left_lca = lowestCommonAncestor(root.left, p, q)
    right_lca = lowestCommonAncestor(root.right, p, q)

    if left_lca and right_lca:
    return root # p and q found in different subtrees
    elif left_lca:
    return left_lca # p/q found in left, or left_lca is LCA
    else:
    return right_lca # p/q found in right, or right_lca is LCA

    In the interview, also mention how to handle cases where p or q might not be present in the tree, and discuss iterative approaches using parent pointers or storing paths.

    ⚡
    Pro Tip

    Pro-Move: BST optimization. Red Flag: O(n) extra space when O(1) possible.

    Want all answers as a PDF for offline study?
    Seven focused volumes with 750+ in-depth answers — Answer Vault →

    Related Python/Coding Questions

    easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

    Level up your prep

    Recommended
    Educative
    Educative Unlimited

    800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

    Start learning →

    Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

    According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

    ← Back to all questionsMore Python/Coding questions →
    Categories
    All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
    By Company
    AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
    Interview Guides
    All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
    Products
    AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
    Company
    About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
    © 2026 DataEngPrep.tech. All rights reserved.
    AboutBlogContactDisclaimer