forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnhistory.js
More file actions
33 lines (27 loc) · 710 Bytes
/
nhistory.js
File metadata and controls
33 lines (27 loc) · 710 Bytes
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
/**
* // Definition for a _Node.
* function _Node(val, neighbors) {
* this.val = val === undefined ? 0 : val;
* this.neighbors = neighbors === undefined ? [] : neighbors;
* };
*/
/**
* @param {_Node} node
* @return {_Node}
*/
var cloneGraph = function (node) {
let visited = {};
const dfs = (node) => {
if (!node) return node;
if (visited[node.val]) return visited[node.val];
let root = new Node(node.val);
visited[node.val] = root;
for (let neighbor of node.neighbors) {
root.neighbors.push(dfs(neighbor));
}
return root;
};
return dfs(node);
};
// TC: O(n+e) -> n: number of nodes | e: number of edges
// SC: O(v) -> v: length of visited object