DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on • Edited on • Originally published at rakeshpeddamallu.netlify.app

Leetcode - 133. Clone Graph

/**
 * // 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)
};
Enter fullscreen mode Exit fullscreen mode

Please do follow the series if you are struggling with leetcode questions 😇

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay