Java easy & fast code

  • 0
    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);
        return graphNode;

Log in to reply

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