//

系统中存在 n 个进程,形成一个有根树结构。给你两个整数数组 pidppid ,其中 pid[i] 是第 i 个进程的 ID ,ppid[i] 是第 i 个进程的父进程 ID 。

// //

每一个进程只有 一个父进程 ,但是可能会有 一个或者多个子进程 。只有一个进程的 ppid[i] = 0 ,意味着这个进程 没有父进程

// //

当一个进程 被杀掉 的时候,它所有的子进程和后代进程都要被杀掉。

// //

给你一个整数 kill 表示要杀掉​​进程的 ID ,返回杀掉该进程后的所有进程 ID 的列表。可以按 任意顺序 返回答案。

// // //

示例 1:

// //
//输入:pid = [1,3,10,5], ppid = [3,0,5,3], kill = 5
//输出:[5,10]
//解释:涂为红色的进程是应该被杀掉的进程。
//
// //

示例 2:

// //
//输入:pid = [1], ppid = [0], kill = 1
//输出:[1]
//
// //

// //

提示:

// // //
Related Topics
  • 深度优先搜索
  • 广度优先搜索
  • 数组
  • 哈希表

  • 👍 87
  • 👎 0
  • package leetcode.editor.cn; import java.util.*; // 582:杀掉进程 public class KillProcess { public static void main(String[] args) { Solution solution = new KillProcess().new Solution(); // TO TEST } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public List killProcess(List pid, List ppid, int kill) { Map> map = new HashMap<>(); for (Integer integer : pid) { map.put(integer, new ArrayList<>()); } map.put(0, new ArrayList<>()); for (int i = 0; i < ppid.size(); i++) { map.get(ppid.get(i)).add(pid.get(i)); } List result = new ArrayList<>(); result.add(kill); Queue queue = new LinkedList<>(); queue.add(kill); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { int key = queue.poll(); List tmps = map.get(key); for (int tmp : tmps) { result.add(tmp); queue.add(tmp); } } } return result; } } //leetcode submit region end(Prohibit modification and deletion) }