Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Lowest Common Ancestor of a Binary Tree

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "236" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [1,2], p = 1, q = 2 Output: 1 Constraints: The number of nodes in the tree is in the range [2, 105]. -109 <= Node.val <= 109 All Node.val are unique. p != q p and q will exist in the tree.

Explanation

Here's the solution to find the Lowest Common Ancestor (LCA) in a binary tree, with a focus on efficiency:

  • Recursive Approach: Traverse the tree recursively. If the current node is one of the target nodes (p or q), return the current node.
  • LCA Logic: If the left and right subtrees both return non-null nodes, it means the current node is the LCA because p is found in one subtree and q in the other.
  • Propagate upwards: If only one subtree returns a non-null node, propagate that node up the call stack, as it could be the LCA or an ancestor of the LCA.

  • Time Complexity: O(N), where N is the number of nodes in the tree. Space Complexity: O(H) in the worst case (skewed tree) and O(log N) in the average case (balanced tree), where H is the height of the tree, due to the recursion stack.

Code

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

def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
    """
    Finds the lowest common ancestor (LCA) of two nodes in a binary tree.

    Args:
        root: The root of the binary tree.
        p: The first node.
        q: The second node.

    Returns:
        The LCA of nodes p and q.
    """

    if not root:
        return None

    if 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
    elif left_lca:
        return left_lca
    else:
        return right_lca

More from this blog

C

Chatmagic blog

2894 posts