My Java solution


  • 2
    O

    consider it is a binary search tree

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    	TreeNode r=root;
    	if(p.val==q.val)return p;
    	while(r!=null){
    		if((p.val-r.val)*(q.val-r.val)<=0)return r;
    		if(p.val>r.val)r=r.right;
    		else
    			r=r.left;
    	}
    	return r;
    }

Log in to reply
 

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