题解 | #牛的奶量统计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);
    }
}

前缀和算法的经典题目,重点是及时删去集合中其他路径和

全部评论

相关推荐

MScoding:你这个实习有一个是当辅导老师,这个和找技术岗没有关系吧?
点赞 评论 收藏
分享
01-24 08:13
已编辑
合肥工业大学 Java
程序员牛肉:没啥问题。标准的流水线简历,但是学历好一点,所以应该是有约面的机会的。 这段时间可以考虑把自己的两个项目彻底的理一理。争取能够讲清楚每一个功能点
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务