forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
employee-importance.py
51 lines (45 loc) · 1.31 KB
/
employee-importance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Time: O(n)
# Space: O(h)
import collections
"""
# Employee info
class Employee(object):
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
self.subordinates = subordinates
"""
class Solution(object):
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
if employees[id-1] is None:
return 0
result = employees[id-1].importance
for id in employees[id-1].subordinates:
result += self.getImportance(employees, id)
return result
# Time: O(n)
# Space: O(w), w is the max number of nodes in the levels of the tree
class Solution2(object):
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
result, q = 0, collections.deque([id])
while q:
curr = q.popleft()
employee = employees[curr-1]
result += employee.importance
for id in employee.subordinates:
q.append(id)
return result