Skip to content

Add code for "Lowest Common Ancestor (LCA) of a Binary Tree" #77

@kumkumverm

Description

@kumkumverm

🚀 Feature Request: Add "Lowest Common Ancestor (LCA) of a Binary Tree" (LeetCode #236)

🧩 Description

I would like to contribute the implementation of the Lowest Common Ancestor (LCA) of a Binary Tree problem.
This algorithm finds the lowest (or deepest) node in a binary tree that is an ancestor of two given nodes.


🧠 Problem Statement

Given a binary tree and two nodes p and q, find their lowest common ancestor (LCA).
The LCA of two nodes p and q is the lowest node in the tree that has both p and q as descendants (a node can be a descendant of itself).

📘 LeetCode Reference: Problem #236 – Lowest Common Ancestor of a Binary Tree


⚙️ Approach

  • Use a recursive approach:
    1. If the current node is null, return null.
    2. If the current node matches either p or q, return the current node.
    3. Recursively search for LCA in the left and right subtrees.
    4. If both sides return non-null, the current node is the LCA.
    5. Otherwise, return the non-null result.

🧮 Time and Space Complexity

  • Time Complexity: O(N), where N is the number of nodes in the tree.
  • Space Complexity: O(H), where H is the height of the tree (due to recursion stack).

💻 Language

  • Java

✅ Checklist

  • I have read the contribution guidelines.
  • My code follows the repository’s coding style.
  • I will add proper test cases and comments.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions