# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = NoneclassSolution:deflowestCommonAncestor(self, root:'TreeNode', p:'TreeNode', q:'TreeNode')->'TreeNode':ifnot root or root == p or root == q:return root
left = right=None# 一定要先声明全局变量if root.val > p.val and root.val > q.val:# 添加判断语句是为了省时间
left = self.lowestCommonAncestor(root.left, p, q)elif root.val < p.val and root.val < q.val:
right = self.lowestCommonAncestor(root.right, p, q)# else: 由于是二叉搜索树,在两边的话,root一定是最近公共祖先# left = self.lowestCommonAncestor(root.left, p, q)# right = self.lowestCommonAncestor(root.right, p, q)return root ifnot left andnot right else left or right