# 9ms java solution

• ``````public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

if ((p.val <= root.val && q.val >= root.val)
|| (p.val >= root.val && q.val <= root.val)) {
return root;
} else if (p.val < root.val && q.val < root.val) {
return lowestCommonAncestor(root.left, p, q);
}else{
return lowestCommonAncestor(root.right, p, q);
}

}
``````

}

• I think we just need to check if both of them are in the left side or the right side. The rest case will be one in each side or either one is ancestor, which we can simply return root.

Version 1:

``````public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p.val < root.val && q.val < root.val)
return lowestCommonAncestor(root.left, p, q);
if(p.val > root.val && q.val > root.val)
return lowestCommonAncestor(root.right, p, q);

return root;
}
}
``````

Version 2:

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

return root;
}
}
``````

Or make it one line:

``````public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return p.val < root.val && q.val < root.val ? lowestCommonAncestor(root.left, p, q) : p.val > root.val && q.val > root.val ? lowestCommonAncestor(root.right, p, q) : root;
}``````

• Your solution's core is same with mine regardless of some details.