```
function lowestCommonAncestor(root, p, q) {
var n = root;
if (n.val > Math.max(p.val, q.val)) {
return lowestCommonAncestor(n.left, p, q);
}
if (n.val < Math.min(p.val, q.val)) {
return lowestCommonAncestor(n.right, p, q);
}
return n;
}
```