【问题标题】:How to implement depth-first search (DFS) on a binary tree in java?如何在java中的二叉树上实现深度优先搜索(DFS)?
【发布时间】:2013-03-06 01:37:19
【问题描述】:

根据the wikipedia article about depth-first search 中的解释,我认为二叉树上的 DFS 与前序遍历根 - 左 - 右(我说的对吗?)相同。

但我只是做了一点搜索,得到了这段代码,其作者声称 DFS 需要一棵树来记录节点是否曾被访问过(或者在图的情况下我们需要这个吗?)。

// 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();
}

谁能解释一下?

【问题讨论】:

    标签: java algorithm


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 说得通,顺便说一句,如果你想 dfs 一棵树(不是二叉树)怎么办?
    • 我修改了通用树的答案。
    【解决方案2】:

    我认为二叉树上的 dps 与前序遍历根 - 左 - 右是相同的。(我是对的吗?)

    深度优先搜索可以是前序、中序或后序遍历。您不需要堆栈:递归实现它更容易,在这种情况下,您也不需要将节点标记为已访问。

    【讨论】:

    • 你能检查一下这个link右边的图片吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多