According to what is explained in the wikipedia article about depth-first search, I think DFS on a binary tree is identical to a preorder traversal root--left--right (am I right?).
But I just did a little search and got this code, the author of which claims that DFS needs a tree to record if the node has been visited before (or do we need this in the case of a graph?).
// copyright belongs to the original author
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();
}
Could anybody explain this?
The depth-first search (DFS) algorithm starts with the initial node of graph G and goes deeper until we find the goal node or the node with no children. Because of the recursive nature, stack data structure can be used to implement the DFS algorithm.
Yes it is preorder. But, I don't really like to say that its a traversal since you might not traverse the tree, you stop as soon as you find your element. The program that you printed is not a search, it's a traversal : you're printing everything. A search function to search in a binary tree would be :
public boolean search(Tree t, int i) {
if(t == null)
return false;
elif(t.value() == i)
return true;
else
for(child in t.children()) {
if(search(child,i))
return true;
}
return false;
//return search(t.leftTree(), i) or search(t.rightTree(),i) binary tree case
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With