二叉搜索树的最近公共祖先二叉搜索树特点:右节点的值大于左节点和根节点,换句话说,如果一个节点的值大于根节点,那么这个节点在根节点的右边,小于根节点则在根节点的左边。要解决这个问题,我们分三种情况:1、如果当前节点的值大于 p 和 q 的值,说明 p 和 q 应该在当前节点的左子树,因此将当前节点移动到它的左子节点;2、如果当前节点的值小于 p 和 q 的值,说明 p 和 q 应该在当前节点的右子树,因此将当前节点移动到它的右子节点;3、如果当前节点的值不满足上述两条要求,那么说明当前节点就是「分岔点」。此时,p 和 q 要么在当前节点的不同的子树中,要么其中一个就是当前节点。不管是哪种,此时的当前节点都是我们要找的最近公共祖先。###def lowestCommonAncestor(self, root, p, q): # Value of current node or parent node. parent_val = root.val # Value of p p_val = p.val # Value of q q_val = q.val # If both p and q are greater than parent if p_val > parent_val and q_val > parent_val: return self.lowestCommonAncestor(root.right, p, q) # If both p and q are lesser than parent elif p_val < parent_val and q_val < parent_val: return self.lowestCommonAncestor(root.left, p, q) # We have found the split point, i.e. the LCA node. else: return root###