Leetcode 113. Path Sum II
题目链接: Path Sum II
难度:Medium
题目大意:
找出二叉树中所有从根节点到叶子节点路径和为target的路径。
思路:
参考高赞回答,用到了递归与回溯。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res=new ArrayList<>();
List<Integer> curList=new ArrayList<>();
dfs(root,targetSum,res,curList);
return res;
}
public void dfs(TreeNode root,int targetSum,List<List<Integer>> res,List<Integer> curList){
if(root==null){
return;
}
curList.add(root.val);
if(root.left==null&&root.right==null&&root.val==targetSum){
res.add(new ArrayList(curList));
//如果直接将curList加进去,后续curList的值改变会导致res中的值也改变,所以要复制一份加进去
}
else{
dfs(root.left,targetSum-root.val,res,curList);
dfs(root.right,targetSum-root.val,res,curList);
}
curList.remove(curList.size()-1);//回溯,删去列表中最后一个节点
}
}