//自己写的,每次都要clone一份currentPath,多了一个currentSum参数:
import java.util.ArrayList;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList> pathSum(TreeNode root, int sum) {
if(root != null) helper(root, sum, 0, new ArrayList());
return result;
}
public void helper(TreeNode node, int sum, int currentSum, ArrayList currentPath){
currentSum += node.val;
currentPath = clone(currentPath);
currentPath.add(node.val);
if(node.left == null && node.right == null){
if(currentSum == sum){
result.add(currentPath);
}
}else {
if(node.left != null) helper(node.left, sum, currentSum, currentPath);
if(node.right != null) helper(node.right, sum, currentSum, currentPath);
}
}
public ArrayList> result = new ArrayList>();
public ArrayList clone(ArrayList arr){
ArrayList copyArr = new ArrayList<>();
for(int value : arr){
copyArr.add(value);
}
return copyArr;
}
}
//参考别人写的,只有在需要根节点满足条件时复制衣服currentPath,使用减法的方式判断是否结果等于sum,减少了中间变量
public class Solution {
public ArrayList> pathSum(TreeNode root, int sum) {
if(root != null) helper(root, sum, new ArrayList());
return result;
}
public void helper(TreeNode node, int sum, ArrayList currentPath){
sum -= node.val;
currentPath.add(node.val);
if(node.left == null && node.right == null){
if(sum == 0){
result.add(new ArrayList(currentPath));
}
}else {
if(node.left != null) helper(node.left, sum, currentPath);
if(node.right != null) helper(node.right, sum, currentPath);
}
currentPath.remove(currentPath.size() - 1);
}
public ArrayList> result = new ArrayList>();
}