Tree: Depth-First Search - Lowest Common Ancestor of Binary Tree
Examine the recursive DFS code below for finding LCA. What is the logical error that causes incorrect results when one node is ancestor of the other?
def LCA(root, p, q):
if not root:
return None
if root == p or root == 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