Throwing stack over flow error, is there any bad recursion , please help me out.


  • 0
    D
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    	if(node  == null) return null;
        UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
        List<UndirectedGraphNode> newNodeNeighbor = new  ArrayList<UndirectedGraphNode>();
        if(node.neighbors!=null&&!node.neighbors.isEmpty()){
        	Iterator iterator =  node.neighbors.iterator();
        	while(iterator.hasNext()){
        		UndirectedGraphNode neighborNode = (UndirectedGraphNode) iterator.next();
        		newNodeNeighbor.add(cloneGraph(neighborNode));
        	}
        }
        newNode.neighbors=newNodeNeighbor;
        return newNode;
    }

  • 1
    S

    You need a mechanism to record whether a node has been traversed. Otherwise, even if the graph has only one loop, your code will stuck in an infinite loop until the stack is exhausted. A good idea might be to make use of a HashMap to store references of all traversed nodes.


  • 0
    D

    thank you, I did not understand why the node should be UNIQUE. Thanks again.


Log in to reply
 

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