Java easy & fast code


  • 0
    D
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        Map<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<>();
        return cloneGraph(node, map);
    }
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node, Map<UndirectedGraphNode, UndirectedGraphNode> map) {
        if(node == null) return null;
        UndirectedGraphNode graphNode = new UndirectedGraphNode(node.label);
        map.put(node, graphNode);
        for (UndirectedGraphNode ugn : node.neighbors) {
            UndirectedGraphNode n = map.containsKey(ugn) ? map.get(ugn) : cloneGraph(ugn, map);
            graphNode.neighbors.add(n);
        }
        return graphNode;
    }

Log in to reply
 

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