5ms simple DFS

  • 0
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
            return helper(node, new HashMap<Integer, UndirectedGraphNode>());
        private UndirectedGraphNode helper(UndirectedGraphNode node, HashMap<Integer, UndirectedGraphNode> visited){
            if(node == null) return null;
            UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
            visited.put(node.label, newNode);
            for(UndirectedGraphNode n : node.neighbors){
                if(visited.containsKey(n.label)) newNode.neighbors.add(visited.get(n.label));
                else newNode.neighbors.add(helper(n, visited));
            return newNode;

Log in to reply

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