The idea is simple: the value of parent must be between p and q, try to find it. If cant, the parent does not exist.

```
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (p == null) return q;
if (q == null) return p;
TreeNode v = p.val < q.val ? p : q;
TreeNode w = p.val > q.val ? p : q;
TreeNode curr = root;
while (curr != null && (curr.val > w.val || curr.val < v.val)) {
if (curr.val < v.val) curr = curr.right;
if (curr.val > w.val) curr = curr.left;
}
return curr;
}
```