# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# 如果走到底仍沒有找到則終止
if not root or not p or not q: return
# 循環條件
while root:
# 如果 p 與 q 都小於 root
if p.val < root.val and q.val < root.val:
root = root.left
# 如果 p 與 q 都大於 root
elif p.val > root.val and q.val > root.val:
root = root.right
# 如果不符合上述條件即是找到
else:
return root