Skip to content

Commit aaf516a

Browse files
committed
Clone Graph
1 parent 3daaeec commit aaf516a

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

clone-graph/TonyKim9401.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// TC: O(n)
2+
// -> visit all elements once for each to clone them
3+
// SC: O(n)
4+
// -> all elements are stored in HashMap and values are limited maximum 2
5+
class Solution {
6+
private Map<Integer, Node> map = new HashMap<>();
7+
public Node cloneGraph(Node node) {
8+
if (node == null) return null;
9+
if (map.containsKey(node.val)) return map.get(node.val);
10+
11+
Node clone = new Node(node.val);
12+
map.put(clone.val, clone);
13+
14+
for (Node neighbor : node.neighbors) {
15+
clone.neighbors.add(cloneGraph(neighbor));
16+
}
17+
return clone;
18+
}
19+
}

0 commit comments

Comments
 (0)