Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement depth-first search (DFS) on a binary tree in java?

Tags:

java

algorithm

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?

like image 768
Accessdenier Avatar asked Mar 06 '13 01:03

Accessdenier


People also ask

What is needed for depth first search DFS implementation?

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.


1 Answers

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
}
like image 174
bruce_ricard Avatar answered Oct 03 '22 02:10

bruce_ricard