注意递归出口:root为null或者左右节点访问完,返回
返回时要注意把path的最后一个数据remove
注意:不能把path直接add到res中。否则更改path的时候。res中的path也会随之而改变。这就是因为res中存的时path的引用,path发生改变时,res中的存储的值会发生相应改变
代码:
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<Integer> path =new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
//int sum=0;
if(root==null){
return res;
}
path.add(root.val);
//sum+=root.val;
if(root.val==target&&root.right==null&&root.left==null){
res.add(new ArrayList<Integer>(path));
}
FindPath(root.left,target-root.val);
FindPath(root.right,target-root.val);
path.remove(path.size()-1);
return res;
}
}