Skip to content

Commit d9ef843

Browse files
committed
solve: clone graph
1 parent 6d99530 commit d9ef843

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

clone-graph/evan.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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.

0 commit comments

Comments
 (0)