forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1490.java
34 lines (31 loc) · 1.02 KB
/
_1490.java
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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.Node;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
public class _1490 {
public static class Solution1 {
public Node cloneTree(Node root) {
if (root == null) {
return root;
}
Map<Node, Node> map = new HashMap<>();
map.put(root, new Node(root.val));
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
Node curr = queue.poll();
for (Node child : curr.children) {
Node childCopy = new Node(child.val);
if (!map.containsKey(child)) {
map.put(child, childCopy);
queue.offer(child);
}
map.get(curr).children.add(childCopy);
}
}
return map.get(root);
}
}
}