定义cur=root,二叉搜索树的最近公共祖先一定介于p和q之间,因此只有在cur同时大于p,q,或者同时小于p,q的时候才需要移动,否则最大祖先就是cur。

class Solution:
    def lowestCommonAncestor(self , root: TreeNode, p: int, q: int) -> int:
        # write code here
        cur = root 
        while (cur.val - p) * (cur.val - q) > 0:
            if cur.val > p:
                cur = cur.left
            else:
                cur = cur.right
        return cur.val