forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJeehay28.js
More file actions
68 lines (56 loc) · 1.53 KB
/
Jeehay28.js
File metadata and controls
68 lines (56 loc) · 1.53 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
67
/**
* // Definition for a _Node.
* function _Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {_Node} node
* @return {_Node}
*/
// BFS approach
// Time Complexity: O(N + E), where N is the number of nodes and E is the number of edges.
// Space Complexity: O(N), due to the clones map and additional storage (queue for BFS, recursion stack for DFS).
var cloneGraph = function (node) {
if (!node) {
return null;
}
let clone = new Node(node.val);
let clones = new Map();
clones.set(node, clone);
let queue = [node];
while (queue.length > 0) {
node = queue.shift();
for (const neighbor of node.neighbors) {
if (!clones.get(neighbor)) {
const temp = new Node(neighbor.val);
clones.set(neighbor, temp);
queue.push(neighbor);
}
clones.get(node).neighbors.push(clones.get(neighbor));
}
}
return clone;
};
// DFS approach
// Time Complexity: O(N + E), where N is the number of nodes and E is the number of edges.
// Space Complexity: O(N), due to the clones map and the recursion stack.
var cloneGraph = function (node) {
if (!node) {
return null;
}
let clones = new Map();
const dfs = (node) => {
if (clones.has(node)) {
return clones.get(node);
}
let clone = new Node(node.val);
clones.set(node, clone);
for (neighbor of node.neighbors) {
clone.neighbors.push(dfs(neighbor));
}
return clone;
};
return dfs(node);
};