Why my code can't pass {0,0,0}


  • 0
    Y
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node==null) return null;
        Set<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
        visited.add(node);
        UndirectedGraphNode cloneNode = new UndirectedGraphNode(node.label);
        cloneGraph(node,cloneNode,visited);
        return cloneNode;
    }
    
    private void cloneGraph(UndirectedGraphNode node,UndirectedGraphNode cloneNode,
                                                      Set<UndirectedGraphNode> visited){
        for(UndirectedGraphNode neighbor: node.neighbors){
           if(visited.contains(neighbor)){
                return;
           }
           visited.add(neighbor);
           UndirectedGraphNode temp =new UndirectedGraphNode(neighbor.label);
           cloneNode.neighbors.add(temp);
           cloneGraph(neighbor,temp,visited);
        }
        return;
    }

  • 0
    G

    Your code can't handle loop, because you immediately return when visited contains neighbor, self-node wouldn't be added to neighbor list.


Log in to reply
 

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