employer cover photo
employer logo
employer logo

Tableau Software

Part of Salesforce

Is this your company?

Tableau Software Interview Question

Clone a Graph

Interview Answer

Anonymous

Feb 19, 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()); } }