5

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?

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

that makes senses, btw, what if you want to dfs a tree(not a binary tree)?
I modified the answer for general trees.
4

I think dps on a binary tree is the same one with preorder traversal root--left--right.(am i right?)

Depth-first search can be pre-, in-, or post-order traversal. You don't need a stack: it's easier to implement it recursively, in which case you don't need to mark nodes as visited either.

1 Comment

Can you check the image at right hand on this link?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.