-
-
Save gennad/791932 to your computer and use it in GitHub Desktop.
Class Main { | |
public void bfs() | |
{ | |
// BFS uses Queue data structure | |
Queue queue = new LinkedList(); | |
queue.add(this.rootNode); | |
printNode(this.rootNode); | |
rootNode.visited = true; | |
while(!queue.isEmpty()) { | |
Node node = (Node)queue.remove(); | |
Node child=null; | |
while((child=getUnvisitedChildNode(node))!=null) { | |
child.visited=true; | |
printNode(child); | |
queue.add(child); | |
} | |
} | |
// Clear visited property of nodes | |
clearNodes(); | |
} | |
public void dfs() { | |
// DFS uses Stack data structure | |
Stack stack = new Stack(); | |
stack.push(this.rootNode); | |
rootNode.visited=true; | |
printNode(rootNode); | |
while(!stack.isEmpty()) { | |
Node node = (Node)s.peek(); | |
Node child = getUnvisitedChildNode(n); | |
if(child != null) { | |
child.visited = true; | |
printNode(child); | |
s.push(child); | |
} | |
else { | |
s.pop(); | |
} | |
} | |
// Clear visited property of nodes | |
clearNodes(); | |
} | |
} | |
Class Node { | |
Char data; | |
Public Node(char c) { | |
this.data=c; | |
} | |
} |
Here's the complete solution:
https://gist.github.com/hmny/44a8738565acd3fc30cf1daf087ebc1c
cool!
In DFS method, why not just use pop() instead of peek()?
What I find odd is that the code marks nodes visited without checking if they've already been visited...
If they've already been visited, shouldn't they be ignored?
Nice implemetation.
you can avoid casting by using type parameters. Queue<Node> queue
Stack<Node> stack
class Node {
List<Node> children;
boolean visited = false;
Node getUnvisitedChildNode(){
return children.stream()
.filter(n -> ! n.visited)
.findFirst().orElse(null);
}
}
@dkonayuki its ok peek, since in DFS she needs to revisit nodes and ask for other children.
Answer @dkonayuki,It would break the stack chain and without missing the right child node, if its use pop().
I realize this is a little pedantic, but these are Breadth and Depth first traversals not searches. They simply visit all nodes, not search for a specific node/value.
Minor issue: getUnvisitedChildNode(node) instead of n.