A Recursive Solution in Java (444ms)


  • 0
    H
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    	if (root == null || p == null || q == null) {
    		if (root == null) {
    			return null;
    		} else if (p == null && q == null) {
    			return root;
    		}
    		return p == null ? q : p;
    	}
    	
    	int bigger = p.val > q.val ? p.val : q.val;
    	int smaller = p.val < q.val ? p.val : q.val;
    	
    	if (root.val > bigger) {
    		return this.lowestCommonAncestor(root.left, p, q);
    	} else if (root.val < smaller) {
    		return this.lowestCommonAncestor(root.right, p, q);
    	} else if (root.val > smaller && root.val < bigger) {
    		return root;
    	} else {
    		return root;
    	}
    }

Log in to reply
 

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