
思路:
递归遍历到叶子结点判断此时路径值的和是否等于目标值
需要注意的点:
1.递归时候传入当前路径数组不能用原数组,不然该数组对象将是所有递归方法共有对象
2.同一getAllPath()方法内在判断左节点递归时候我们在currentSum上和currList上加的数据要去掉,避免对右节点判断时候传入的值造成影响
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
ArrayList<ArrayList<Integer>> pathList = new ArrayList<>();
ArrayList<Integer> currList = new ArrayList<>();
if (root==null){
return pathList;
}
getAllPath(root, target, 0, currList, pathList);
return pathList;
}
private void getAllPath(TreeNode root, int target, int currentSum, ArrayList<Integer> currList, ArrayList<ArrayList<Integer>> pathList) {
if (root.left == null && root.right == null) {
if (target == root.val + currentSum) {
currList.add(root.val);
pathList.add(currList);
}
return;
}
if (root.left != null) {
currentSum += root.val;
currList.add(root.val);
getAllPath(root.left, target, currentSum, new ArrayList<>(currList), pathList);
currentSum-=root.val;
currList.remove(currList.size()-1);
}
if (root.right != null) {
currentSum += root.val;
currList.add(root.val);
getAllPath(root.right, target, currentSum, new ArrayList<>(currList), pathList);
}
不知道为什么这里没用排序也通过了测试用户,按照题目说的我们要根据字典序打印所有路径,其实这里就是要根据数组长度由大到小去打印路径的,所以建议大家再return pathList前加一句Collections.sort(pathList,(list1,list2)->list2.size()-list1.size());
网友评论