A very clean python solution with DFS


  • 0
    P
    class Solution(object):
        def copyRandomList(self, head):
            """
            :type head: RandomListNode
            :rtype: RandomListNode
            """
            # use DFS to visit the graph
            # DFS info must be stored within visited
            # here visited is the nodeMap
            self.nodeMap = {}
            return self.DFS(head)
            
        def DFS(self, node):
            if not node: return None
            if node not in self.nodeMap: # visited
                self.nodeMap[node] = RandomListNode(node.label)
                self.nodeMap[node].next = self.DFS(node.next)
                self.nodeMap[node].random = self.DFS(node.random)
            return self.nodeMap[node]

Log in to reply
 

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