Fast Java solution


  • 0
    S
        public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
            Map<Integer, List<Integer>> processTree = new HashMap<Integer, List<Integer>>();
            int total = pid.size(), i;
            
            for (i=0;i<total;i++) {
                Integer process = pid.get(i);
                Integer parent = ppid.get(i);
                
                if (parent != 0) {
                    List<Integer> children = processTree.get(parent);
                    if (children == null) {
                        children = new ArrayList<Integer>();
                    }
                    children.add(process);
                    processTree.put(parent, children);
                } else if(parent == kill)
                    return pid;
            }
            
            List<Integer> result = new ArrayList<>();
            Queue<Integer> queue = new LinkedList<Integer>();
            queue.add(kill);
            while (!queue.isEmpty()) {
                Integer child = queue.poll();
                result.add(child);
                List<Integer> children = processTree.get(child);
                if (children != null)
                    queue.addAll(children);
            }
            return result;
        }
    }

Log in to reply
 

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