11ms java solution, 3 lines

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

• this solution is not complete. It assumes root, p, q are not null and p, q exist on the tree.

• the better one :

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

• @sean23 @FrankBian I think u guys can improve without recursion

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

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.