1. # Definition for a binary tree node.
    2. # class TreeNode:
    3. # def __init__(self, x):
    4. # self.val = x
    5. # self.left = None
    6. # self.right = None
    7. class Solution:
    8. def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
    9. if root == None or root == p or root == q:
    10. return root
    11. left = self.lowestCommonAncestor(root.left, p, q)
    12. right = self.lowestCommonAncestor(root.right, p, q)
    13. if left != None and right != None:
    14. return root
    15. if left != None:
    16. return left
    17. if right != None:
    18. return right
    19. return None