题解 | #牛的奶量统计II#
牛的奶量统计II
https://www.nowcoder.com/practice/9c56daaded6b4ba3a9f93ce885dab764
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param targetSum int整型 * @return bool布尔型 */ HashSet<Integer> set = new HashSet<>(); boolean flag = false; public boolean hasPathSumII(TreeNode root, int targetSum) { // write code here if (root == null) { return false; } set.add(0); dfs(root, root.val, targetSum); return flag; } private void dfs(TreeNode root, int sum, int target) { if (set.contains(sum - target)) { flag = true; } set.add(sum); if(root.left != null) dfs(root.left, sum + root.left.val, target); set.remove(sum); if(root.right != null) dfs(root.right, sum + root.right.val, target); } }
前缀和算法的经典题目,重点是及时删去集合中其他路径和