Java solution - parent to children HashMap


  • 0
    public class Solution {
        public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
            if(kill == 0) {
                return pid;
            }
            List<Integer> killed = new ArrayList<>();
            Map<Integer, List<Integer>> children = new HashMap<>();
            int counter = 0;
            for(Integer parent : ppid) {
                Integer child = pid.get(counter);
                if(children.get(parent) == null) {
                    List<Integer> childs = new ArrayList<>();
                    childs.add(child);
                    children.put(parent, childs);
                }
                else {
                    children.get(parent).add(child);
                }
                counter++;
            }
            
            kill(children, kill, killed);
            return killed;
        }
        
        private void kill(Map<Integer, List<Integer>> children, int kill, List<Integer> killed) {
            killed.add(kill);
            List<Integer> childs = children.get(kill);
            if(childs == null) {
                return;
            }
            for(Integer child : childs) {
                kill(children, child, killed);
            }
        }
    }
    

Log in to reply
 

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