Suppose node connects to node , and node connects back to node . When you clone node , you recurse into node . Cloning node tries to recurse back into node . Without protection, this loops forever.
The fix: use a hash map from original nodes to their copies. Before cloning any node, check the map first. If the node already has a copy, return it immediately. This breaks the cycle. You must add each node to the map before recursing into its neighbors.