Node with 0 or 1 parents

输入是int[][] input, input[0]是input[1] 的parent,比如 {{1,4}, {1,5}, {2,5}, {3,6}, {6,7}}会形成上面的图 第一问是只有0个parents和只有1个parent的节点

  1    2    3
/  \  /      \
4    5        6
                \
                  7
 public List<Integer> findNodesWithZeroOrOneParent(int[][] edges)
    {
        List<Integer> res = new ArrayList<Integer>();
        // child -- > set of its parents
        Map<Integer, Set<Integer>> map = new HashMap<>();
        for(int i = 0; i< edges.length; i++)
        {
            int parent  = edges[i][0];
            int child = edges[i][1];
            map.putIfAbsent(child, new HashSet<Integer>());
            map.get(child).add(parent);
        }

        for(Map.Entry<Integer, Set<Integer>> entry : map.entry.Set())
        {
            if(entry.getValue().size() <=1)
            {
                res.add(entry.getKey());
            }
        }
        return res;
    }

Last updated