# @lc code=start
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None or root is q or root is p:
return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
# 兵分两路,搜查而已,那一条路上找到了有价值的p或者q就向上汇报
# 没一个节点都会汇总情况,没有找到有价值的那一路就不用向上汇报了
if l is not None and r is not None:
return root
elif l is not None and r is None:
return l
elif l is None and r is not None:
return r
else:
return None