113. 路径总和 II - 力扣(LeetCode) (leetcode-cn.com)
?整个树的遍历过程符合回溯的遍历节点过程,所以选择回溯作为框架
代码如下
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
int sum = 0;
if (root==null)return res;
rootnum(root,targetSum,temp,sum);
return res;
}
public void rootnum(TreeNode root ,int targetSum,List<Integer> temp ,int sum){
if(root ==null){
return;
}
temp.add(root.val);
if(sum+root.val == targetSum&&root.left==null&&root.right==null){
res.add(new ArrayList<>(temp));
}
rootnum(root.left,targetSum,temp,sum+root.val);
rootnum(root.right,targetSum,temp,sum+root.val);
temp.remove(temp.size()-1);//回溯
}
}
|