My Python solution with dictionary

  • 6
       def cloneGraph(self, node):
            if not node:
                return None
            return self.createNode(node)
        def createNode(self, oldNode):
            newNode = UndirectedGraphNode(oldNode.label)
            self.newNodeDict[newNode.label] = newNode
            for i in oldNode.neighbors:
                if i.label not in self.newNodeDict:
                    self.createNode(i) #recursively create nodes
            return newNode

Log in to reply

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