Created
December 1, 2019 04:20
-
-
Save shixiaoyu/6486442619b07c93beceaf7d7cc25174 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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