Created
December 1, 2019 04:22
-
-
Save shixiaoyu/4ae59e07c8b5151151a3b232a3f22a1f 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
// exactly the same as BFS except used a stack to mimic the recursion, technically any BFS can be written | |
// in DFS by using a stack | |
public Node cloneGraphDFSUsingStack(Node node) { | |
if (node == null) { | |
return node; | |
} | |
Map<Node, Node> lookup = new HashMap<>(); | |
Node t = new Node(node.val, new ArrayList<>()); | |
lookup.put(node, t); | |
Stack<Node> stack = new Stack<>(); | |
stack.push(node); | |
while (!stack.isEmpty()) { | |
Node cur = stack.pop(); | |
for (Node n : cur.neighbors) { | |
Node copiedNeighbor = null; | |
if (!lookup.containsKey(n)) { | |
copiedNeighbor = new Node(n.val, new ArrayList<>()); | |
stack.push(n); | |
lookup.put(n, copiedNeighbor); | |
} else { | |
copiedNeighbor = lookup.get(n); | |
} | |
lookup.get(cur).neighbors.add(copiedNeighbor); | |
} | |
} | |
return lookup.get(node); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment