```
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return null;
// both p and q are less than root
// their ancestor must be in root.left
if (p.val < root.val && q.val < root.val)
return lowestCommonAncestor(root.left, p, q);
// both p and q are greater than root
// their ancestor must be in root.right
if (p.val > root.val && q.val > root.val)
return lowestCommonAncestor(root.right, p, q);
return root;
}
}
```