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?

4

2 回答 2

5

是的,这是预购。但是,我不太喜欢说它是遍历,因为您可能不会遍历树,一旦找到元素就停止。您打印的程序不是搜索,而是遍历:您正在打印所有内容。在二叉树中搜索的搜索函数是:

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
}
于 2013-03-06T01:57:03.107 回答
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.

于 2013-03-06T01:40:33.113 回答