Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 732f764

Browse files
Add solution to 133.
1 parent 2132fcc commit 732f764

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

‎solutions/0133.clone-graph.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val, neighbors) {
4+
* this.val = val === undefined ? 0 : val;
5+
* this.neighbors = neighbors === undefined ? [] : neighbors;
6+
* };
7+
*/
8+
9+
/**
10+
* @param {Node} node
11+
* @return {Node}
12+
*/
13+
var cloneGraph = function (node) {
14+
const visited = {};
15+
16+
var cloneHelper = function (node) {
17+
if (node === null) {
18+
return null;
19+
}
20+
21+
if (visited[node.val]) {
22+
return visited[node.val];
23+
}
24+
25+
const clonedNode = new Node(node.val, []);
26+
visited[node.val] = clonedNode;
27+
28+
for (let n of node.neighbors) {
29+
clonedNode.neighbors.push(cloneHelper(n));
30+
}
31+
32+
return clonedNode;
33+
};
34+
35+
return cloneHelper(node);
36+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /