二叉树的公共祖先有四种情况:
1.左右子树都没有寻找的节点,此时返回None
2.两个值分布在左右子树的两侧,此时返回root
3.q为祖先,前提是除q下的子树,无法找到p值
4.p为祖先,前提是除p下的子树,无法找到q值
def helper(root,p,q):
if not root:return None
if root==p or root==q: return root
left=helper(root.left,p,q)
right=helper(root.right,p,q)
# 四种情况
# 左右子树都没有
if not left and not right:
return None
# 在树的两侧:
if left and right:
return root
# 在左子树上:
if left and not right:
return left
if right and not left:
return right
return root
return helper(root,p,q)