class Solution:
def lowestCommonAncestor(self, root, p, q):
while root:
if root.val > p.val and root.val > q.val:
root = root.left
elif root.val < p.val and root.val < q.val:
root = root.right
else:
return root
Python Iterative Solution

A small (math) trick to make it shorter :
if the value of x is between a and b, then (xa)*(xb)<=0def lowestCommonAncestor(self, root, p, q): while (root.valp.val)*(root.valq.val) > 0: if root.val > max(p.val, q.val): root = root.left else: root = root.right return root
same idea but even shorter (Python!):
def lowestCommonAncestor(self, root, p, q): while (root.valp.val)*(root.valq.val) > 0: root = (root.right, root.left)[root.val>max(p.val, q.val)] return root