133. Clone Graph

DFS

/**
 * @param {Node} node
 * @return {Node}
 */

let m;
var cloneGraph = function (node) {
    if (node === null) 
        return null;
    
    m = new Map();
    return dfs(node);
};

function dfs(node) {

    if (m.get(node.val) !== undefined) 
        return m.get(node.val);
    
    const cloned = new Node(node.val, []);
    m.set(node.val, cloned);
    
    for (const there of node.neighbors) {
        cloned.neighbors.push(dfs(there));
    }

    return cloned;
}
Console

Iteration

time: O(n)

space: O(n)

Last updated