Java DFS Solution


  • 0

    Just build the adjacency list and do a dfs to get all children of kill

        public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
            Map<Integer, List<Integer>> map = new HashMap<>();
            for(int i = 0; i < pid.size(); i++) {
                List<Integer> children = map.getOrDefault(ppid.get(i), new ArrayList<>());
                children.add(pid.get(i));
                map.put(ppid.get(i), children);
            }
            List<Integer> result = new ArrayList<>();
            dfs(map, kill, result);
            return result;
        }
        private void dfs(Map<Integer, List<Integer>> map, int kill, List<Integer> result) {
            result.add(kill);
            if(!map.containsKey(kill)) return;
            List<Integer> children = map.get(kill);
            for(Integer child : children) {
                dfs(map, child, result);
            }
        }
    

Log in to reply
 

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