-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path133. Clone Graph
41 lines (35 loc) · 907 Bytes
/
133. Clone Graph
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
36
37
38
39
40
41
//https://leetcode.com/problems/clone-graph/
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node *cloneGraph(Node *node) {
if (node == nullptr)
return nullptr;
else
return cloneGraphHelper(node);
}
private:
unordered_map<int, Node *> record;
Node *cloneGraphHelper(Node *node) {
auto new_node = new Node(node->val);
record[new_node->val] = new_node;
for(auto n : node->neighbors) {
if(record.count(n->val)) {
new_node->neighbors.push_back(record[n->val]);
} else {
new_node->neighbors.push_back(cloneGraphHelper(n));
}
}
return new_node;
}
};