Simple Java solution Root to Leaf Paths With Sum


#1

public class Solution {
int sum=0;
ArrayList<ArrayList> ans = new ArrayList<ArrayList>();
public int check(TreeNode A,int B,int sum,ArrayList be)
{
if(A==null)
return 0;
else if(A.left==null && A.right==null && A.val+sum == B)
{
be.add(A.val);
ArrayList temp = new ArrayList();
for(int i=0;i<be.size();i++)
temp.add(be.get(i));
ans.add(temp);
be.remove(be.size()-1);
return 0;
}
else if(A.val+sum != B && A.left==null && A.right==null)
return 0;
else
{
be.add(A.val);
check(A.left,B,sum+A.val,be);
check(A.right,B,sum+A.val,be);
be.remove(be.size()-1);
return 0;
}
}
public ArrayList<ArrayList> pathSum(TreeNode A, int B) {

    sum =0;
    ans.clear();
    ArrayList<Integer> be = new ArrayList<Integer>();
    check(A,B,sum,be);
    return ans;
}

}