/**
* // 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) {
if (!node) return null;
let visited = new Map();
const dfs = (original) =>{
if (!original) return null;
if(visited.has(original.val)){
return visited.get(original.val)
}else{
const copy = new Node(original.val,[]);
visited.set(copy.val, copy);
original?.neighbors.forEach((nei)=>{
copy.neighbors.push(dfs(nei));
})
return copy
}
}
return dfs(node)
};
Please do follow the series if you are struggling with leetcode questions š
Top comments (0)