题目
思路
该题目中员工的层级关系组织成了一棵树,然而实际存储过程并没有按照树数据结构存储(只存储了id,没有存储数据结点)。为了实现快速通过id访问数据结点,我们首先需要将员工数据存储到hash表中。
之后就需要以一个员工为根节点遍历员工层级树,将遍历过程中的所有结点相加,可以使用DFS或者BFS,下边的代码使用了BFS。
代码
/*
// Definition for Employee.
class Employee {
public:
int id;
int importance;
vector<int> subordinates;
};
*/
class Solution {
public:
int getImportance(vector<Employee*> employees, int id) {
unordered_map<int, Employee*> eps;
queue<Employee*> q;
int result = 0;
for(Employee* ep : employees) {
eps[ep->id] = ep;
}
Employee* ep;
ep = eps[id];
q.push(ep);
while(!q.empty()) {
ep = q.front();
q.pop();
result += ep->importance;
for(int sid : ep->subordinates) {
q.push(eps[sid]);
}
}
return result;
}
};