-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloneGraph.cpp
More file actions
27 lines (21 loc) · 771 Bytes
/
cloneGraph.cpp
File metadata and controls
27 lines (21 loc) · 771 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
class Solution {
unordered_map<Node*, Node*> visited;
public:
Node* cloneGraph(Node* node) {
//use a hashmap to track the already cloned nodes
//recursively iterate through the graph until completion
if(!node) return nullptr;
//if already clones return the clone
if (visited.find(node) != visited.end()) {
return visited[node];
}
//create a new node
Node* clone = new Node(node->val);
visited[node] = clone;
//clone neighbors recursively
for (Node* nei : node->neighbors) {
clone->neighbors.push_back(cloneGraph(nei));
}
return clone;
}
};