JavaScript solution


  • 0
    L
    function cloneGraph(graph) {
    
      if (!graph) return graph;
      var map = {};
      return traverse(graph);
    
      function traverse(node) {
        if (!map[node.label]) {
          var newNode = new UndirectedGraphNode(node.label);
          map[node.label] = newNode;
          newNode.neighbors = node.neighbors.map(traverse);
        }
        return map[node.label];
      }
    }

  • 0
    G

    @linfongi this solution is beautiful. Thanks for sharing.


Log in to reply
 

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