您的位置:首页 > 游戏 > 手游 > Leetcode 113:路径总和II

Leetcode 113:路径总和II

2024/10/17 7:29:07 来源:https://blog.csdn.net/xiao_xiao_wang_/article/details/139129060  浏览:    关键词:Leetcode 113:路径总和II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

public static  List<List<Integer>> pathSum(TreeNode root, int targetSum) {List<List<Integer>> res=new ArrayList<>();List<Integer> list=new ArrayList<>();   //记录每一个符合要求的路径if(root==null) return res;res=findPathSum(root,res,list,targetSum);return res;}public static List<List<Integer>> findPathSum(TreeNode node, List<List<Integer>> path,List<Integer> list,int targetSum){list.add(node.val);//先判断是否当前节点是否为叶子节点if(node.left==null && node.right==null){int sum=0;for(int i=0;i<list.size();i++){sum=sum+list.get(i);}if(sum==targetSum) {List<Integer> res=new ArrayList<>(list);//path.add(list)中存储的为list对象,之后对list的任何操作都会影响结果//path.add(new ArrayList<>(list)) 时,path 中存储的是 list 的一个副本,与list内容相同,但是为不同对象path.add(new ArrayList<>(list));   //符合要求,则加入path中};}//不为叶子节点时if(node.left!=null){findPathSum(node.left,path,list,targetSum);list.remove(list.size()-1);}if(node.right!=null){findPathSum(node.right,path,list,targetSum);list.remove(list.size()-1);}return path;}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com