The crux of this problem is that both nodes have to be in a subtree, so you want to check if the node is either p or q, in which case the node is the LCA. If the LCA is either the left or right hand side, then it is also the current node. Otherwise, you want to return either the left or right hand node.
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
def lca(root, p, q):
if not root or root in [p, q]:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left and right:
return root
return left or right
return lca(root, p, q)