VISUALGO//PROBLEMS
lowest common ancestor of a binary tree · binary tree – dfsmedium
LeetCode #236
tree
351620874
p
·
q
·
lca
·
ELEMENTS
root
p
q
Python
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
    if root is None or root is p or root is q:
        return root

    left = lowestCommonAncestor(root.left, p, q)
    right = lowestCommonAncestor(root.right, p, q)
    if left and right:
        return root  # p and q are on different sides
    return left or right  # pass up whatever was found