这个题也是用递归的思路来做的,从根节点开始,弄一个sum,和目标值比较,然后依次左右,直到叶结点。且总和相等。
如果中途sum就超过了target,就直接舍弃这一条路。
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if(root == null){
return result;
}
find(root,0,target,new ArrayList<>(),result);
return result;
}
public void find(TreeNode node, int sum, int target, ArrayList<Integer> list,ArrayList<ArrayList<Integer>> result){
if(node==null && sum==target && !result.contains(list)){
result.add(list);
return;
}
if(node == null){
return;
}
sum += node.val;
list.add(node.val);
if(sum>target){
return;
}
find(node.left,sum,target,new ArrayList<>(list),result);
find(node.right,sum,target,new ArrayList<>(list),result);
}
}