Graph traversal, that is, BFS, the difference is that each point of the left and right nodes are not known beforehand, is to create the time to add in
1 Publicundirectedgraphnode Clonegraph (Undirectedgraphnode node) {2 if(node = =NULL) {3 return NULL;4 }5queue<undirectedgraphnode> queue =NewLinkedlist<undirectedgraphnode>();6Undirectedgraphnode NewNode =NewUndirectedgraphnode (Node.label);7 queue.offer (node);8Map<undirectedgraphnode, undirectedgraphnode> map =NewHashmap<undirectedgraphnode, undirectedgraphnode>();9 map.put (node, newNode);Ten while(!Queue.isempty ()) { OneUndirectedgraphnode cur =Queue.poll (); A for(Undirectedgraphnode neighbor:cur.neighbors) { -Undirectedgraphnode Newneighbor =Map.get (neighbor); - if(!Map.containskey (neighbor)) { theNewneighbor =NewUndirectedgraphnode (Neighbor.label); - map.put (neighbor, Newneighbor); - Queue.add (neighbor); - } + map.get (cur). Neighbors.add (Newneighbor); - } + } A returnNewNode; at}
133. Clone Graph