forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClone N-ary Tree.java
More file actions
46 lines (41 loc) · 1003 Bytes
/
Clone N-ary Tree.java
File metadata and controls
46 lines (41 loc) · 1003 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {
children = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
children = new ArrayList<Node>();
}
public Node(int _val,ArrayList<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public Node cloneTree(Node root) {
if (root == null) {
return root;
}
Queue<Node> queue = new LinkedList<>();
Map<Node, Node> map = new HashMap<>();
queue.add(root);
map.put(root, new Node(root.val));
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
Node removed = queue.remove();
for (Node child : removed.children) {
queue.add(child);
map.put(child, new Node(child.val));
map.get(removed).children.add(map.get(child));
}
}
}
return map.get(root);
}
}