# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None
classSolution: deflowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # 基线条件 if root==None: returnNone # 后续 从下往上找 公共点。 left = self.lowestCommonAncestor(root.left,p,q) right = self.lowestCommonAncestor(root.right,p,q) if (left and right) or root==p or root==q: return root elif left==Noneand right==None: returnNone elif left and right==None: return left elif left==Noneand right: return right