Since it's a binary search tree, the idea becomes very simple: once p and q ends up on the left and right subtree, the current root is the LCA (assume `p.val <= q.val`

).

```
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val > q.val) {
TreeNode temp = p;
p = q;
q = temp;
}
return LCA(root, p, q);
}
private TreeNode LCA(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return root;
if (p.val <= root.val && q.val >= root.val) {
return root;
}
if (root.val > q.val) {
return LCA(root.left, p, q);
}
if (root.val < p.val) {
return LCA(root.right, p, q);
}
return null;
}
}
```