一定要记住每次走到最后要把path最后一个Node删除
/**
* 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<>();
List<Integer> path = new ArrayList<>();
helper(root, sum, res, path);
return res;
}
public void helper(TreeNode root, int sum, List<List<Integer>> res, List<Integer> path){
if (root == null){
return;
}
//add current node into list
path.add(new Integer(root.val));
if (root.left == null && root.right == null && root.val == sum){
res.add(new ArrayList<Integer>(path));
return;
}
if(root.left != null){
helper(root.left, sum-root.val, res, path);
path.remove(path.size()-1);
}
if(root.right != null){
helper(root.right, sum-root.val, res, path);
path.remove(path.size()-1);
}
}
}