思路
利用一个哈希表,把员工id作为key值,把员工信息(Employee)作为value值,再利用深度优先遍历即可
解题过程
把查询员工的重要度加入返回值,再dfs算法将下属员工的重要度加入返回值(如果下属员工还有下属员工,也利用dfs加入,以此类推)
Code
/*
// Definition for Employee.
class Employee {
public int id;
public int importance;
public List<Integer> subordinates;
};
*/
class Solution {
public int getImportance(List<Employee> employees, int id) {
Map<Integer,Employee> map=new HashMap<>();
for(Employee e:employees){
map.put(e.id,e);
}
return dfs(map,id);
}
public int dfs(Map<Integer,Employee> map,int id){
Employee e=map.get(id);
int ans=e.importance;
for(int i:e.subordinates){
ans+=dfs(map,i);
}
return ans;
}
}