Recursive JS solution


  • 0
    R
    var graphTable;
    
    function cloneGraphRec(graph) {
        graphTable[graph.label] = new UndirectedGraphNode(graph.label);
        for(var i = 0; i < graph.neighbors.length; i++) {
            if(graphTable[graph.neighbors[i].label] === undefined)
                graphTable[graph.label].neighbors.push(cloneGraphRec(graph.neighbors[i]));
            else
                graphTable[graph.label].neighbors.push(graphTable[graph.neighbors[i].label]);
        }
        return graphTable[graph.label];
    }
    
    function cloneGraph(graph) {
        graphTable = {};
        return (graph === null ? null : cloneGraphRec(graph));
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.