Simple Python iterative DFS


  • 2
    L
      def getImportance(self, employees, id):
            """
            :type employees: Employee
            :type id: int
            :rtype: int
            """
            d={e.id:e for e in employees}
            ret=0
            stk=[d[id]] #we can go straight to the employee since we have a map already
            while stk: 
                top=stk.pop()
                ret+=top.importance
                for n in top.subordinates:
                    stk.append(d[n])
            return ret

  • 0
    T

    This solution works under the assumption that there are no cycles in the graph as it does not keep track of the nodes visited and check against them before adding to the stack.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.