LeetCode 1490 Clone N-ary Tree
deep copy of a N-ary.
we met many problems like this: clone something(deep copy)
this is exactly the same with deep copy of a graph.
the core of this problem is: a very clear mind about what that hashmap do. and how to copy a new node with same node value and same children list.
class Solution {
public Node cloneTree(Node root) {
if (root == null) return null;
LinkedList<Node> queue = new LinkedList<>();
HashMap<Node, Node> visited = new HashMap<Node, Node>();
queue.offer(root);
visited.put(root, new Node(root.val, new ArrayList<>()));
while (!queue.isEmpty()) {
Node cur = queue.poll();
int size = cur.children.size();
for (int i = 0; i < size; i++) {
//if (cur.children.get(i) != null) stack.push(cur.children.get(i));
if (!visited.containsKey(cur.children.get(i))) {
visited.put(cur.children.get(i), new Node(cur.children.get(i).val, new ArrayList<>()));
queue.offer(cur.children.get(i));
}
visited.get(cur).children.add(visited.get(cur.children.get(i)));
}
}
return visited.get(root);
}
}

浙公网安备 33010602011771号