30 Day Challenge Day 19 | Leetcode 1490. Clone N-ary Tree
题解
Medium
BFS
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
Node* cloneTree(Node* root) {
if(!root) return nullptr;
Node* copy = new Node(root->val);
unordered_map<Node*, Node*> m;
m[root] = copy;
queue<Node*> q;
q.push(root);
while(!q.empty()) {
Node* n = q.front();
q.pop();
for(Node* next : n->children) {
if(!m.count(next)) {
q.push(next);
copy = new Node(next->val);
m[next] = copy;
m[n]->children.push_back(copy);
}
}
}
return m[root];
}
};