Skip to content

Instantly share code, notes, and snippets.

@danielrobertson
Created July 10, 2016 00:25
Show Gist options
  • Save danielrobertson/6abaef32c587ec11813d19e8f617a201 to your computer and use it in GitHub Desktop.
Save danielrobertson/6abaef32c587ec11813d19e8f617a201 to your computer and use it in GitHub Desktop.
Tree searches - BST and DFS
void dfs(Node r) {
if(r == null)
return;
visit(r);
r.visited = true; // avoid cycles
for(Node n : r.adjacent) {
if(!n.visited)
dfs(n);
}
}
void bfs(Node r) {
Queue<Node> q = new Queue<Node>();
q.enqueue(r);
while(!q.isEmpty()) {
Node n = q.dequeue();
if(!n.visited) {
visit(n);
for(Node i : n.adjacent) {
q.enqueue(i);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment