Java BFS&HashMap


  • 0
    H
    public static List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        for(int i=0;i<ppid.size();i++){
            if(map.containsKey(ppid.get(i))){
                map.get(ppid.get(i)).add(pid.get(i));
            }else{
                List<Integer> temp = new ArrayList<>();
                temp.add(pid.get(i));
                map.put(ppid.get(i), temp);
            }
        }
        List<Integer> res = new ArrayList<>();
    
        Queue<Integer> queue = new LinkedList<>();
        queue.add(kill);
        while(!queue.isEmpty()){
            int parent = queue.poll();
            res.add(parent);
            List<Integer> child = map.get(parent);
            if(child!=null)
                queue.addAll(child);
        }
        return res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.