File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ // Definition for a Node.
3
+ class Node {
4
+ public int val;
5
+ public List<Node> neighbors;
6
+ public Node() {
7
+ val = 0;
8
+ neighbors = new ArrayList<Node>();
9
+ }
10
+ public Node(int _val) {
11
+ val = _val;
12
+ neighbors = new ArrayList<Node>();
13
+ }
14
+ public Node(int _val, ArrayList<Node> _neighbors) {
15
+ val = _val;
16
+ neighbors = _neighbors;
17
+ }
18
+ }
19
+ */
20
+
21
+ class Solution {
22
+ HashMap <Node , Node > nodeMap = new HashMap <>(); // key: original Node, value: copied Node
23
+
24
+ public Node cloneGraph (Node node ) {
25
+ if (node == null ) return null ;
26
+
27
+ if (nodeMap .containsKey (node )) {
28
+ return nodeMap .get (node );
29
+ }
30
+
31
+ Node newNode = new Node (node .val );
32
+ nodeMap .put (node , newNode );
33
+
34
+ for (Node neighborNode : node .neighbors ) {
35
+ newNode .neighbors .add (cloneGraph (neighborNode ));
36
+ }
37
+
38
+ return newNode ;
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments