Graph Theory37 sections · 1633 units
Open in Course

Implementation - Recursive LCA

(Pseudocode)

Here is the recursive LCA implementation for binary trees:

function lowestCommonAncestor(root, p, q):
    // Base cases
    if root is null:
        return null
    if root == p or root == q:
        return root

    // Recursively search left and right subtrees
    left = lowestCommonAncestor(root.left, p, q)
    right = lowestCommonAncestor(root.right, p, q)

    // If both sides found something, current node is LCA
    if left and right:
        return root

    // Otherwise, return whichever side found something
    return left if left else right

Time: O(n)O(n) where nn is the number of nodes. Space: O(h)O(h) for recursion stack.