Better java solution, but cannot pass 30/31, why?


  • 0
    I

    I dont understand why this is not passing all test cases? Any idea?
    '''
    public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root == null || root.val == p.val || root.val == q.val)
    {
    return root;
    }

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        if(left!=null && left.val != p.val && left.val != q.val)
        {
            return left;
        }
        
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(right!=null && right.val != p.val && right.val != q.val)
        {
            return right;
        }
        
        if(left!=null && right != null)
        {
            return root;
        }
        return left == null? right : left;
    }
    

    }
    '''


  • 0
    N

    @IoTLeetCoder try comparing objects p.q and not their values and you should pass all 31 cases


  • 0
    I

    @niteshthakur Thanks, it passed. I don't understand though...


  • 0
    N

    The objects p,q are provided as input and not the values. The values could be duplicate in the tree but the objects will be unique.


Log in to reply
 

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