Skip to content

Instantly share code, notes, and snippets.

@mding5692
Created October 27, 2016 04:35
Show Gist options
  • Save mding5692/3360267509c752d27a724848732d090b to your computer and use it in GitHub Desktop.
Save mding5692/3360267509c752d27a724848732d090b to your computer and use it in GitHub Desktop.
Review of BFS & DFS
// pretends Node is like this:
/* Node {
int data;
List<Integer> neighbors;
}
*/
public Node bfs(Node head, int findInt) {
Node result = new Node(-1); // null node basically
if (head == null) {
return null;
}
if (head.data == findInt) {
return head;
}
Queue<Node> q = new LinkedList<>();
q.offer(head);
while (q.peek()!=null) {
if (currNode.data == findInt) {
result = currNode;
break;
}
Node currNode = q.poll();
for (Node n : currNode.neighbors) {
q.offer(n);
}
}
return result;
}
public Node dfs(Node head, int findInt) {
if (head == null) return null;
if (head.data == findInt) {
return head;
}
Stack<Node> s = new Stack<>();
s.push(head);
Node result = new Node(-1);
while (!s.empty()) {
Node currNode = s.pop();
if (currNode.data == findInt) {
result = currNode
break;
}
for (Node n: currNode.neighbors) {
s.push(n);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment