The main idea is to check three situations:

1.p and q are on the different sides of the root, then return root

2.p and q both are on the left side of root, search recursively until No. 1 happens Or p or q equals the root

3.p and q both are on the right side of root, search recursively until No. 1 happens Or p or q equals the root

```
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
else if(Math.max(p.val, q.val) < root.val){
if(root.left == p) return p;
else if(root.left == q) return q;
else return lowestCommonAncestor(root.left, p, q);
}
else if(Math.min(p.val, q.val) > root.val){
if(root.right == p) return p;
else if(root.left == q) return q;
else return lowestCommonAncestor(root.right, p, q);
}
else return root;
}
}
```