My Java Recursive Solution


  • 1
    R
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        	if(root == null || p == null || q ==null)
        		return null;
        	TreeNode max = (p.val > q.val)?p:q;
        	TreeNode min = (p.val > q.val)?q:p;
        	if(root.val <= max.val && root.val >= min.val)
        		return root;
        	else if(root.val > max.val){
        		root = root.left;
        	}else{
        		root = root.right;  		
        	}
        	return lowestCommonAncestor(root, p, q);      
        }
    }

  • 0
    S

    You don't need min and max if you move the first if to the end .

    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 return root;

Log in to reply
 

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