Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created December 1, 2019 04:20
Show Gist options
  • Save shixiaoyu/6486442619b07c93beceaf7d7cc25174 to your computer and use it in GitHub Desktop.
Save shixiaoyu/6486442619b07c93beceaf7d7cc25174 to your computer and use it in GitHub Desktop.
public Node cloneGraphDFSWithRecursion(Node node) {
if (node == null) {
return node;
}
Map<Node, Node> lookup = new HashMap<>();
return this.cloneGraphHelper(node, lookup);
}
/**
* A dfs helper using recursion to make a copy of each node recursively via neighbors
* @param node
* @param lookup
* @return the copied node of Node
*/
private Node cloneGraphHelper(Node node, Map<Node, Node> lookup) {
if (node == null) {
return node;
}
if (lookup.containsKey(node)) {
return lookup.get(node);
}
Node copiedNode = new Node(node.val, new ArrayList<>());
lookup.put(node, copiedNode);
for (Node n : node.neighbors) {
Node copiedN = this.cloneGraphHelper(n, lookup);
copiedNode.neighbors.add(copiedN);
}
return copiedNode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment