Given a node in a graph node
, clone the graph, and return the cloned node.
When you modify the cloned graph, it should have no effect on the original graph. This means that you can't simply return the original node as the solution to the problem.
0. Problem
We want to write a function that takes in a node
, and returns its clone.
1. Recursion
To write the recursion, we first have to copy the current node. After we do this, we need to point the node to the clones of its neighbor nodes, like this:
Here's the recursion:
2. Base case
We need to make sure we don't enter any infinite cycles since we're dealing with graphs. We should stop if we get to a node we've already cloned. This way we never clone the same node twice, so our code can't possibly run forever.
To do this, we'll store all the nodes we've visited in a HashMap called cloneOfNode
. Here's the base case:
3. Code
Here's the full code:
Time Complexity O(n). We visit every node in the graph.
Space Complexity O(n). We store every node in the HashMap cloneOfNode
.