Recursive DFS Java solution using HashMap

  • 2
        public HashMap<Integer, UndirectedGraphNode> graph = new HashMap<Integer, UndirectedGraphNode>();
    	public UndirectedGraphNode DFS(UndirectedGraphNode node) {
    		UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
    		graph.put(newNode.label, newNode);
    		for(UndirectedGraphNode neighbor : node.neighbors) {
    			if(!graph.containsKey(neighbor.label)) {
    		return newNode;
    	public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    		if(node == null) return null;
    		return DFS(node);

Log in to reply

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