路径总和2
https://leetcode-cn.com/problems/path-sum-ii
给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
叶子节点 是指没有子节点的节点
public class PathSum2 {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> ans=new ArrayList<>();
if(root==null){
return ans;
}
//path:存储从根节点到各个节点的路径。
ArrayList<Integer> path=new ArrayList<>();
process(root,path,0,targetSum,ans);
return ans;
}
//root:根节点。path:存储从根节点到各个节点的路径。preSum:前缀和。targetSum:目标和。ans:返回的链表的链表
public void process(TreeNode root,List<Integer> path,int preSum,int targetSum,List<List<Integer>> ans){
//只有是叶节点,而且前缀和加根节点的和等于目标和,才可以将此路径加入到ans中,而且是复制的path。不能直接讲path加入到ans中,因为path是动态变化的。
if(root.left==null&&root.right==null){
if(preSum+root.val==targetSum){
path.add(root.val);
ans.add(copyArray(path));
//remove是进行恢复现场操作,回到上一步,即上一个节点。
path.remove(path.size()-1);
}
}
//preSum是值传递,因此,不用改变preSum的值。
preSum+=root.val;
//
path.add(root.val);
//左子树不为null,递归左子树。
if(root.left!=null){
process(root.left,path,preSum,targetSum,ans);
}
//右子树不为null,递归右子树
if(root.right!=null){
process(root.right,path,preSum,targetSum,ans);
}
//恢复现场,返回根节点。
path.remove(path.size()-1);
}
public List<Integer> copyArray(List<Integer> list){
List<Integer> copy=new ArrayList<>();
for(Integer i:list){
copy.add(i);
}
return copy;
}
}