File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import Optional
2+
3+
4+ class Node :
5+ def __init__ (self , val = 0 , neighbors = None ):
6+ self .val = val
7+ self .neighbors = neighbors if neighbors is not None else []
8+
9+
10+ class Solution :
11+ def cloneGraph (self , node : Optional ["Node" ]) -> Optional ["Node" ]:
12+ if node is None :
13+ return None
14+
15+ copied = {}
16+
17+ def traverse (node : Optional ["Node" ]) -> Optional ["Node" ]:
18+ if node in copied :
19+ return copied [node ]
20+
21+ newNode = Node (node .val )
22+ copied [node ] = newNode
23+ newNode .neighbors = [traverse (neighbor ) for neighbor in node .neighbors ]
24+
25+ return newNode
26+
27+ return traverse (node )
28+
29+
30+ # Time Complexity: O(n), where n is the number of nodes in the graph, reflecting that each node is visited exactly once.
31+ # Space Complexity: O(n), where n is the number of nodes in the graph.
32+ # This accounts for the space needed to store a copy of each node
33+ # and the maximum potential size of the recursion call stack, which corresponds to the number of nodes.
You can’t perform that action at this time.
0 commit comments