File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time Complexity: O(N + E) - visit each node once and for each node, we iterate through its neighbors O(E).
2+ # Space Complexity: O(N) - store a copy of each node in the hashmap O(N).
3+
4+ class Solution :
5+ def cloneGraph (self , node ):
6+ if node is None :
7+ return None
8+
9+ # dictionary to keep track of cloned nodes (original -> clone)
10+ mp = {}
11+
12+ def clone (node ):
13+ if node in mp :
14+ # if the node has already been cloned, return the copy
15+ return mp [node ]
16+
17+ # create a new node with the same value
18+ cpy = Node (node .val )
19+ # store it in the map so don't clone it again
20+ mp [node ] = cpy
21+
22+ # clone all neighbors and add them to the new node's neighbors list
23+ for n in node .neighbors :
24+ cpy .neighbors .append (clone (n ))
25+
26+ return cpy
27+
28+ return clone (node )
You can’t perform that action at this time.
0 commit comments