NeetCode - Lowest Common Ancestor In Binary Search Tree

🧾 Problem Description

Given a binary search tree (BST) where all node values are unique, and two nodes from the tree p and q, return the lowest common ancestor (LCA) of the two nodes.

The lowest common ancestor between two nodes p and q is the lowest node in a tree T such that both p and q as descendants. The ancestor is allowed to be a descendant of itself.

🧠 My Python Solution

Solution 1

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    # Helper function to find path from root to target node
    def find_path(self, node, target, path):
        if not node:
            return False
        
        path.append(node)

        if node.val == target.val:
            return True

        if self.find_path(node.left, target, path) or self.find_path(node.right, target, path):
            return True
        
        path.pop()
        return False

    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        path_p = []
        path_q = []

        found_p = self.find_path(root, p, path_p)
        found_q = self.find_path(root, q, path_q)

        if not found_p or not found_q:
            return None  # One of the nodes was not found in the tree

        i = 0
        while i < len(path_p) and i < len(path_q) and path_p[i] == path_q[i]:
            i += 1

        return path_p[i - 1]

Solution 2

Reference: Lowest Common Ancestor of a Binary Search Tree - Leetcode 235 - Python

class Solution:
    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        cur = root

        while cur:
            if p.val > cur.val and q.val > cur.val:
                cur = cur.right
            elif p.val < cur.val and q.val < cur.val:
                cur = cur.left
            else:
                return cur
    
        return None

💡 Thought Process