请问为什么找到了一条符合条件的root to leaf path之后不return呢?
也就是if (pathSum == target){ res.add(new ArrayList<Integer>(list)); }
这里为什么不直接return了?我一开始写写了return 然后就错了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null){
return res;
}
List<Integer> list = new ArrayList<>();
helper(res, list, root, sum);
return res;
}
private void helper(List<List<Integer>> res, List<Integer> list, TreeNode root, int target){
if (root == null){
return;
}
list.add(root.val);
if (root.left == null && root.right == null){
int pathSum = 0;
for (int i = 0; i < list.size(); i++){
pathSum += list.get(i);
}
if (pathSum == target){
res.add(new ArrayList<Integer>(list));
}
}
helper(res, list, root.left, target);
helper(res, list, root.right, target);
list.remove(list.size() - 1);
}
}