Recursion, Trees
class Node(object): # ...
def count_employees(self):
"""Return a count of how many employees this person manages.
Return a count of how many people that manager manages. This should
include *everyone* under them, not just people who directly report to
them.
"""
# START SOLUTION
count = 0
for child in self.children:
count = count + 1 + child.count_employees()
return count
You could also do this non-recursively, using a loop:
class Node(object): # ...
def count_employees_nonrecursive(self):
"""Return a count of how many employees this person manages.
Return a count of how many people that manager manages. This should
include *everyone* under them, not just people who directly report to
them.
Non-recursive version.
"""
# Using a loop, also a fine way to solve this, although it's
# probably a little trickier and less elegant than the
# recursive version
count = 0
to_visit = [self]
while to_visit:
emp = to_visit.pop()
for child in emp.children:
count += 1
to_visit.append(child)
return count