# Why does this code give time limit exceeded? Java

• ``````/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
get(root,sum,0,list,bigList);
return bigList;
}
if (node == null) return;
int number = sum + node.val;
if (number == target && node.left == null && node.right == null){// leaf & target check
return;
}
else {
//recurse
if (node.left != null) get(node.left, target, number, list, bigList);
if (node.right != null) get(node.right, target, number, list, bigList);
}
}

}
``````

For the test case:
[1,1,#,1,#...,1,#,1] 1000"

• my code has the same approach and also has same issue.

• You know in Java, if you use the object as parameter, then in the recursive function the parameter will always refer to the same object, which means the list you used is keep adding without removing element... And I guess the answer shall be wrong too.. Here is my code, though it looks ugly..

``````public class Solution {
List<List<Integer>> result = new ArrayList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null)
return result;
calculate(root,sum,new ArrayList<Integer>());
return result;
}
public void calculate(TreeNode root,int sum,List<Integer> path){
if(root.left==null&&root.right==null){
if(sum-root.val==0){
}
}
else{
if(root.left!=null)
calculate(root.left,sum-root.val,path);
if(root.right!=null)
calculate(root.right,sum-root.val,path);
}
path.remove(path.size()-1);
return;
}
``````

}

cheers~

• Thanks a lot. I should have copied contents to a newly initialized list before the next recursive calls.

• In the last line, what you missed is deleting "node.val" from list, which you added previously.
You need to "undo" the change you made to list, at the end of each recursion.
I think you may not just end up with TLE, but also wrong answer.

• your answer is wrong , you should define a new List when a recursive start

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