114路径总和2

路径总和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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值