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: where is the number of nodes. Space: for recursion stack.