235. Lowest Common Ancestor of a Binary Search Tree (Easy) - TengnanYao/daily_leetcode GitHub Wiki

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        # iteration
        small = min(p.val, q.val)
        large = max(p.val, q.val)
        while root:
            if small <= root.val <= large:
                return root
            if large < root.val:
                root = root.left
            else:
                root = root.right
                
        # recursion
        if root.val < p.val and root.val < q.val:
            return self.lowestCommonAncestor(root.right, p, q)
        elif root.val > p.val and root.val > q.val:
            return self.lowestCommonAncestor(root.left, p, q)
        else:
            return root