Very easy to understand Java DFS solution


  • 0
    T
    public class Solution {
        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++){
                int child = pid.get(i);
                int parent = ppid.get(i);
                List<Integer> list;
                if(map.containsKey(parent)){
                    list = map.get(parent);
                }else{
                    list = new ArrayList<Integer>();
                    map.put(parent, list);
                }
                list.add(child);
            }
            
            List<Integer> result = new ArrayList<>();
            result.add(kill);
            helper(map, map.get(kill), result);
            return result;
        }
        
        private void helper(Map<Integer, List<Integer>> map, List<Integer> list, List<Integer> result){
            if(list == null) return;
            
            for(int temp: list){
                result.add(temp);
                helper(map, map.get(temp), result);
            }
        }
    }

Log in to reply
 

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