You have n processes forming a rooted tree structure. You are given two integer arrays pid and ppid, where pid[i] is the ID of the ith process and ppid[i] is the ID of the ith process’s parent process.
Each process has only one parent process but may have multiple children processes. Only one process has ppid[i] = 0, which means this process has
no parent process (the root of the tree).
When a process is killed , all of its children processes will also be killed.
Given an integer kill representing the ID of a process you want to kill, return a list of the IDs of the processes that will be killed. You may return the answer inany order.

Input: pid =[1,3,10,5], ppid =[3,0,5,3], kill =5Output: [5,10]Explanation: The processes colored in red are the processes that should be killed.
Killing a process means killing all its descendants in the process tree. We can build a parent-to-children mapping and traverse from the kill node to collect all affected processes.
classSolution {
public List<Integer>killProcess(List<Integer> pid, List<Integer> ppid, int kill) {
Map<Integer, List<Integer>> tree =new HashMap<>();
for (int i = 0; i < pid.size(); ++i)
tree.computeIfAbsent(ppid.get(i), x ->new ArrayList<>()).add(pid.get(i));
List<Integer> ans =new ArrayList<>();
Queue<Integer> q =new LinkedList<>();
q.offer(kill);
while (!q.isEmpty()) {
int cur = q.poll();
ans.add(cur);
for (int ch : tree.getOrDefault(cur, List.of())) q.offer(ch);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funkillProcess(pid: List<Int>, ppid: List<Int>, kill: Int): List<Int> {
val tree = mutableMapOf<Int, MutableList<Int>>()
for (i in pid.indices) tree.getOrPut(ppid[i]) { mutableListOf() }.add(pid[i])
val ans = mutableListOf<Int>()
val q = ArrayDeque<Int>()
q.add(kill)
while (q.isNotEmpty()) {
val cur = q.removeFirst()
ans.add(cur)
tree[cur]?.forEach { q.add(it) }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defkillProcess(self, pid: list[int], ppid: list[int], kill: int) -> list[int]:
from collections import defaultdict, deque
tree: dict[int, list[int]] = defaultdict(list)
for c, p in zip(pid, ppid):
tree[p].append(c)
ans: list[int] = []
q = deque([kill])
while q:
cur = q.popleft()
ans.append(cur)
q.extend(tree[cur])
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use std::collections::{HashMap, VecDeque};
impl Solution {
pubfnkill_process(pid: Vec<i32>, ppid: Vec<i32>, kill: i32) -> Vec<i32> {
letmut tree = HashMap::new();
for (&c, &p) in pid.iter().zip(ppid.iter()) {
tree.entry(p).or_insert(vec![]).push(c);
}
letmut ans =vec![];
letmut q = VecDeque::new();
q.push_back(kill);
whilelet Some(cur) = q.pop_front() {
ans.push(cur);
iflet Some(children) = tree.get(&cur) {
for&ch in children { q.push_back(ch); }
}
}
ans
}
}