Created
October 27, 2016 04:35
-
-
Save mding5692/3360267509c752d27a724848732d090b to your computer and use it in GitHub Desktop.
Review of BFS & DFS
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
// 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; | |
} |
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 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