Your code might be failing for larger test cases LCA


#1

Solution works without any issues but it says, “Your code might be failing for larger test cases” Doesnt give me the inputs too to checkout. It gave me partial points only. How do I check for which input it is failing for? Do you guys find any possible issues with this code?

public class Solution {
    
    private boolean addToPath(ArrayList<Integer> path, int val) {
        // System.out.println(val);
        path.add(0, val);
        return true;
    }
    
    public boolean path(TreeNode A, int val, ArrayList<Integer> path) {
        if (A == null) {
            return false;
        }
        if (A.val == val) {
            addToPath(path, val);
            return true;
        }
        return ((path(A.left, val, path) && addToPath(path, A.left.val)) || (path(A.right, val, path) && addToPath(path, A.right.val)));
    }
    
    public int lca(TreeNode A, int B, int C) {
        ArrayList<Integer> pathOfB = new ArrayList<Integer>();
        ArrayList<Integer> pathOfC = new ArrayList<Integer>();
        
        if (path(A, B, pathOfB)) {
            addToPath(pathOfB, A.val);
        }
        if (path(A, C, pathOfC)) {
            addToPath(pathOfC, A.val);
        }
        // System.out.println(pathOfB);
        // System.out.println(pathOfC);
        
        if (pathOfB.size() == 0 || pathOfC.size() == 0) {
            return -1;
        }
        
        int length = Math.min(pathOfB.size(), pathOfC.size());
        for (int i = 1; i < length; i ++) {
            if (pathOfB.get(i) != pathOfC.get(i)) {
                return pathOfB.get(i - 1);
            }
        }
        return  pathOfB.get(length - 1);
    }
}

#2

Try to use “equals” instead of “!=” operator


#3

i am facing the same issue
my approach is same and i am getting runtime exception for larger test cases

public int lca(TreeNode A, int B, int C) {
     List<Integer> pathtonode1 = new ArrayList<Integer>();
List<Integer> pathTonode2 = new ArrayList<Integer>();

getRootToNodePath(A, pathtonode1, B);
getRootToNodePath(A, pathTonode2, C);

Collections.reverse(pathtonode1);
Collections.reverse(pathTonode2);

if(pathtonode1.size() ==0 || pathTonode2.size() ==0){
  return -1;
}

int i;
for (i = 0; i < pathtonode1.size() && i < pathTonode2.size() ; i++)
  if (pathtonode1.get(i) != pathTonode2.get(i))
    break;
return pathtonode1.get(i-1);

}

private int getRootToNodePath(TreeNode root , List<Integer> arr, int node){
if(root == null)
  return -1;

if(root.val == node){
  arr.add(root.val);
  return 1;
}
int k1 = getRootToNodePath(root.left , arr, node);
int k2 = getRootToNodePath(root.right, arr, node);

if(k1 ==1 || k2==1){
  arr.add(root.val);
  return 1;
}
return -1;

}