This problem remember one thing, using HashMap as data structure:
class Solution { Map<Integer, Node> map = new HashMap<>(); public Node cloneGraph(Node node) { if(node==null) return null; return clone(node); } private Node clone(Node node){ if(!map.containsKey(node.val)){ Node newNode = new Node(node.val); map.put(node.val, newNode); List<Node> neighbors = node.neighbors; for(Node neighbor: neighbors){ clone(neighbor); newNode.neighbors.add(clone(neighbor)); } return newNode; }else return map.get(node.val); } }