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);
        
    }
}

 

posted on 2022-04-12 07:03  阳光明媚的菲越  阅读(12)  评论(0编辑  收藏  举报