当前位置: 首页 > 后端技术 > Java

LeetCode-113-PathSumII

时间:2023-04-01 18:18:43 Java

PathSumII题目描述:给定你的二叉树的根节点root和一个整数目标和targetSum,找出从根节点到叶节点的所有路径,其和等于给定的目标总和。叶节点是没有子节点的节点。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:层序遍历使用Queue>>结构记录当前节点的路径和路径之和,其中:外层Pair的key为当前节点;layerpair的key是当前路径的总和,value是当前路径的记录,从根节点到当前节点。然后使用层序遍历的方法,使用队列遍历二叉树的节点。当判断一个节点的左右节点都为空时,就是叶子节点,然后判断当前路径值是否等于targetSum。如果相等,则将相应的路径添加到集中的结果中。最后返回结果集。importcom.kaesar.leetcode.TreeNode;importjavafx.util.Pair;importjava.util.*;publicclassLeetCode_113{//结果集privatestaticList>result=newArrayList<>();publicstaticList>pathSum(TreeNoderoot,inttargetSum){if(root==null){returnnewArrayList<>();/***外层Pair的key是当前节点*内层Pair的key是当前路径的总和,value是当前路径的记录,从根节点到当前节点*/Queue>>>nodes=newLinkedList<>();Listpath=newArrayList<>();添加路径(root.val);//初始化,将根节点加入队列nodes.add(newPair<>(root,newPair<>(root.val,path)));//while(!nodes.isEmpty()){Pair>>cur=nodes.poll();树节点curNode=cur.getKey();//判断当前节点左右节点为空,为叶子节点,然后判断当前路径值是否等于targetSumif(curNode.left==null&&curNode.right==null){如果(cur.getValue().getKey()==targetSum){result.add(cur.getValue().getValue());}继续;}//如果当前节点不是叶子节点,则继续遍历if(curNode.left!=null){ListleftPath=newArrayList<>(Arrays.asList(newInteger[cur.getValue().getValue().size()]));Collections.copy(leftPath,cur.getValue().getValue());leftPath.add(curNode.left.val);nodes.add(新对<>(curNode.left,新对<>(cur.getValue().getKey()+curNode.left.val,leftPath)));}if(curNode.right!=null){ListrightPath=newArrayList<>(Arrays.asList(newInteger[cur.getValue().getValue().size()]));收藏.copy(rightPath,cur.getValue().getValue());rightPath.add(curNode.right.val);nodes.add(新对<>(curNode.right,新对<>(cur.getValue().getKey()+curNode.right.val,rightPath)));}}返回结果;}publicstaticvoidmain(String[]args){TreeNoderoot=newTreeNode(1);root.left=newTreeNode(2);root.right=newTreeNode(3);root.right.left=newTreeNode(4);root.right.right=newTreeNode(5);for(Listintegers:pathSum(root,8)){for(Integerinteger:integers){System.out.print(integer+"");}System.out.println();}}}【每日留言】命运不过是失败者无聊的自慰。懦夫的嘲讽人的未来只能由自己的意志和自己的努力来决定。