Created
July 10, 2016 00:25
-
-
Save danielrobertson/6abaef32c587ec11813d19e8f617a201 to your computer and use it in GitHub Desktop.
Tree searches - BST and DFS
This file contains 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
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