-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloneGraph
More file actions
34 lines (26 loc) · 738 Bytes
/
cloneGraph
File metadata and controls
34 lines (26 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
class Solution {
map<Node*, Node*> visited;
public:
Node* clone(Node* node) {
if (node == nullptr)
return nullptr;
// already cloned
if (visited.find(node) != visited.end()) {
return visited[node];
}
// create new node
Node* temp = new Node(node->val);
// mark as visited BEFORE cloning neighbors (important for cycles)
visited[node] = temp;
// clone neighbors
for (Node* neigh : node->neighbors) {
temp->neighbors.push_back(clone(neigh));
}
return temp;
}
Node* cloneGraph(Node* node) {
if (node == nullptr)
return nullptr;
return clone(node);
}
};