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 in any order.
Example 1:
Input: pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
Output: [5,10]
Explanation: The processes colored in red are the processes that should be killed.
Killing a process kills its whole descendant tree. The parent arrays should become an adjacency list first.
\(g[p]\) stores children of \(p\). DFS or BFS from kill gathers every reachable id. Each process is entered once.
We first construct a graph \(g\) based on \(pid\) and \(ppid\), where \(g[i]\) represents all child processes of process \(i\). Then, starting from the process \(kill\), we perform depth-first search to obtain all killed processes.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of processes.
Killing a process also kills every descendant. The parent links arrive as two parallel arrays, and \(n\) can be \(5 \times 10^4\), so each process should first store its children. Collecting descendants by recursion along a parent chain uses a call depth equal to the process count and overflows Python once the chain reaches length \(1000\). A stack therefore holds the processes still to visit: a popped process is recorded, and its children are pushed in reverse so the collection order matches a preorder walk of the child lists. The process tree has no cycle, so each process is pushed once.
Build a graph \(g\) from \(pid\) and \(ppid\), where \(g[i]\) is the list of child processes of process \(i\). Start at process \(kill\) and walk with an explicit stack. When process \(i\) is popped, append it to the answer and push its children in reverse order, so the earlier child is popped next. Every descendant is collected once. The problem accepts the ids in any order.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the number of processes.