class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null) return null;
if(root.val>p.val && root.val>q.val){
TreeNode l = lowestCommonAncestor(root.left,p,q);
if(l!=null) return l;
}
if(root.val<p.val && root.val<q.val){
TreeNode r = lowestCommonAncestor(root.right,p,q);
if(r!=null) return r;
}
return root;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(root!=null){
if(root.val > p.val && root.val > q.val) root=root.left;
else if(root.val < p.val && root.val < q.val) root=root.right;
else break;
}
return root;
}
}