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
66 lines (59 loc) · 1.33 KB
/
Clone N-ary Tree.java
File metadata and controls
66 lines (59 loc) · 1.33 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
// 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 null;
}
Node copy = new Node(root.val);
for (Node child : root.children) {
copy.children.add(cloneTree(child));
}
return copy;
}
Map<Node, Node> map;
public Node cloneTreeDetailed(Node root) {
if (root == null) {
return null;
}
map = new HashMap<>();
copyTree(root);
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node removed = queue.remove();
Node copy = map.get(removed);
List<Node> children = removed.children;
for (Node child : children) {
copy.children.add(map.get(child));
queue.add(child);
}
}
return map.get(root);
}
private void copyTree(Node root) {
if (root == null) {
return;
}
map.put(root, new Node(root.val));
for (Node child : root.children) {
copyTree(child);
}
}
}