Easy Java Solution with Stack


#1

Stack temp=new Stack();
public void sum(TreeNode A, int B, ArrayList<ArrayList> ans)
{
if(A==null)
{
return;
}
ArrayList inter=new ArrayList();
temp.push(A.val);
//System.out.println(A.val);
sum(A.left,B,ans);
int sum1=0;
if(A.left==null && A.right==null)
{
Iterator value = temp.iterator();
while (value.hasNext()) {
sum1+=value.next();
}
// System.out.println(“sum”+sum1);
if(sum1==B)
{
for (Integer item: temp)
{
inter.add(item);
}
ans.add(inter);
}
}
sum(A.right,B,ans);
temp.pop();

}

   
public ArrayList<ArrayList<Integer>> pathSum(TreeNode A, int B) {
     ArrayList<ArrayList<Integer>> ans=new ArrayList<ArrayList<Integer>>();
    
    sum( A,B,ans);
    return ans;
}

#2

nice work …