原题目:https://leetcode-cn.com/problems/employee-importance/
代码:
先采用哈希,把id和元素对应起来,方便查找,然后使用队列,进行广度优先搜索。
代码:
class Solution {
public:
int getImportance(vector<Employee*> employees, int id) {
map<int,Employee*> m;
for(auto e:employees){
m[e->id] = e;
}
int sum = 0,tmp;
queue<Employee*> q;
q.push(m[id]);
while(!q.empty()){
Employee* p = q.front();
q.pop();
for(auto e:p->subordinates){
q.push(m[e]);
}
sum += p->importance;
}
return sum;
}
};
深度优先搜索的代码:
class Solution {
private:
int sum = 0;
map<int,Employee*>m;
public:
void dfs(int id){
sum += m[id]->importance;
for(auto t:m[id]->subordinates){
dfs(t);
}
return;
}
int getImportance(vector<Employee*> employees, int id) {
for(auto e:employees){
m[e->id] = e;
}
dfs(id);
return sum;
}
};