-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
41 lines (38 loc) · 949 Bytes
/
Solution.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
35
36
37
38
39
40
41
/**
* Definition for Node.
* public class Node {
* int val;
* Node left;
* Node right;
* Node random;
* Node() {}
* Node(int val) { this.val = val; }
* Node(int val, Node left, Node right, Node random) {
* this.val = val;
* this.left = left;
* this.right = right;
* this.random = random;
* }
* }
*/
class Solution {
private Map<Node, NodeCopy> mp;
public NodeCopy copyRandomBinaryTree(Node root) {
mp = new HashMap<>();
return dfs(root);
}
private NodeCopy dfs(Node root) {
if (root == null) {
return null;
}
if (mp.containsKey(root)) {
return mp.get(root);
}
NodeCopy copy = new NodeCopy(root.val);
mp.put(root, copy);
copy.left = dfs(root.left);
copy.right = dfs(root.right);
copy.random = dfs(root.random);
return copy;
}
}