I have the following python code for this problem accepted, but I am wondering if the iterative solution is better than recursive ones in this case. Because I read some other question, and it seems that most people are doing it in iterative way. So I am just wondering if there is any catch here that iterative solution is preferable? Thanks.
class Solution: # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if not node: return None return self._cloneGraph(node, dict()) def _cloneGraph(self, node, visited): # if node.labe is already visited, just return it if node.label in visited: return visited[node.label] # clone the node cloned = UndirectedGraphNode(node.label) # add the node to visited map visited[cloned.label] = cloned # clone each neighbor for neighbor in node.neighbors: cloned.neighbors.append(self._cloneGraph(neighbor, visited)) return cloned