Sollicitatievraag bij Tableau Software

Clone a Graph

Antwoord op sollicitatievraag

Anoniem

19 feb 2016

// Note: This is based on a stack overflow article ! //Assuming a graph consists of a data payload and a list of children: import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; class GraphNode { T data; GraphNode(T data) { this.data = data; } final List children = new ArrayList(); private GraphNode cloner(Map copies) { GraphNode copy = copies.get(this); if (copy == null) { copy = new GraphNode(data); // Map the new node _before_ copying children. copies.put(this, copy); for (GraphNode child : children) copy.children.add(child.clone(copies)); } return copy; } public GraphNode clone() { return cloner(new HashMap()); } }