原题链接
本人的思路见下图:
![](https://img-blog.csdnimg.cn/c12622f535bb4c9d9ab7232d4e8dddbf.png)
代码:
class Solution:
def lowestCommonAncestor(self , root: TreeNode, p: int, q: int) -> int:
# write code here
if p == root.val or q == root.val:
return root.val
elif (p < root.val and q > root.val) or (p > root.val and q < root.val): # 一个在左子树,一个在右子树
return root.val
elif p < root.val and q < root.val: # 全在左子树
return self.lowestCommonAncestor(root.left, p, q)
else: # 全在右子树
return self.lowestCommonAncestor(root.right, p, q)