Given n processes, each process has a unique PID (process id) and its PPID (parent process id).
Each process only has one parent process, but may have one or more children processes. This is just like a tree structure. Only one process has PPID that is 0, which means this process has no parent process. All the PIDs will be distinct positive integers.
We use two list of integers to represent a list of processes, where the first list contains PID for each process and the second list contains the corresponding PPID.
Now given the two lists, and a PID representing a process you want to kill, return a list of PIDs of processes that will be killed in the end. You should assume that when a process is killed, all its children processes will be killed. No order is required for the final answer.
Example 1:
Input: pid = [1, 3, 10, 5] ppid = [3, 0, 5, 3] kill = 5 Output: [5,10] Explanation: 3 / \ 1 5 / 10 Kill 5 will also kill 10.
Note:
- The given kill id is guaranteed to be one of the given PIDs.
- n >= 1.
We can view the given process relationships in the form of a tree. We can construct the tree in such a way that every node stores information about its own value as well as the list of all its direct children nodes. Thus, now, once the tree has been generated, we can simply start off by killing the required node, and recursively killing the children of each node encountered rather than traversing over the whole ppid array for every node as done in the previous approach.
In order to implement this, we've made use of a Node class which represents a node of a tree. Each node represents a process. Thus, every node stores its own value(Node.val) and the list of all its direct children(Node.children). We traverse over the whole pid array and create nodes for all of them. Then, we traverse over the ppid array, and make the parent nodes out of them, and at the same time add all their direct children nodes in their Node.children list. In this way, we convert the given process structure into a tree structure.
public class Solution {
public List<Integer> killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
HashMap<Integer, Node> map= new HashMap<Integer, Node>();
for(Integer i : pid){
Node node = new Node(i);
map.put(i, node);
}
for(int i=0; i<ppid.size(); i++){
if(ppid.get(i) > 0){
Node par = map.get(ppid.get(i));
par.children.add(map.get(pid.get(i)));
}
}
List<Integer> list = new ArrayList<Integer>();
list.add(kill);
getAllChildren(list, map.get(kill));
return list;
}
public void getAllChildren(List<Integer> list, Node kill){
for(Node n : kill.children){
list.add(n.val);
getAllChildren(list, n);
}
}
public class Node{
int val;
List<Node> children = new ArrayList<Node>();
public Node(int val){
this.val = val;
}
}
}