forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClone Graph.java
More file actions
35 lines (29 loc) · 738 Bytes
/
Clone Graph.java
File metadata and controls
35 lines (29 loc) · 738 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {}
public Node(int _val,List<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
Map<Node, Node> map = new HashMap<>();
public Node cloneGraph(Node node) {
if (node == null) {
return null;
}
if (map.containsKey(node)) {
return map.get(node);
}
Node newNode = new Node(node.val, new ArrayList<>());
map.put(node, newNode);
for (Node n : node.neighbors) {
newNode.neighbors.add(cloneGraph(n));
}
return newNode;
}
}