简体   繁体   English

BFS,DFS搜索需要标记为访问树?

[英]BFS, DFS searches required to mark as Visited for trees?

Looking at the BFS and DFS algorithms they seem to mark the nodes as visited. 查看BFS和DFS算法,他们似乎将节点标记为已访问。 If I am navigating trees only is it still necessary for my implementation to mark nodes as visited or not? 如果我正在浏览树只是我的实现仍然需要将节点标记为已访问或未访问? I want to perform some action on every node exactly once. 我想在每个节点上执行一次操作。

It seems it would be only required for graphs, where cycles exist, creating the possibility that I could bump into the same node twice. 似乎只需要存在周期的图形,这样就有可能两次撞到同一个节点。 If I do the calls recursively for a tree, it does not seem necessary to have a visited status as I can chose to perform the action I want on the node after all the calls from the stack return to the current node. 如果我以递归方式为树执行调用,则似乎没有必要具有访问状态,因为在从堆栈的所有调用返回到当前节点之后,我可以选择在节点上执行我想要的操作。 Is my assumption correct? 我的假设是否正确?

Thanks. 谢谢。

Your assumption is correct, the marking is needed only with data-structures that have cycles, since trees don't have cycles - you can remove the marking part from your implementation and BFS/DFS should still work! 您的假设是正确的,只有具有循环的数据结构才需要标记,因为树没有循环 - 您可以从实现中删除标记部分,BFS / DFS仍然可以工作!

Example: in-order traverse of a tree is actually running a DFS with an additional "rule" that you always visit the left child first. 示例:树的按顺序遍历实际上正在运行带有附加“规则”的DFS,您始终首先访问左侧子项。

Python: 蟒蛇:

def in-order(node):
    if not node:
        return
    in-order(node.get_left())
    print(node)
    in-order(node.get_right())

Your assumption is correct for directed trees. 您的假设对于定向树是正确的。

For undirected trees - if you choose not to mark all visited nodes - you should send an additional variable in the recursion that will tell which neighbor of the current node was already traversed (his parent node in the DFS traverse). 对于无向树 - 如果您选择不标记所有被访问的节点 - 您应该在递归中发送一个附加变量,该变量将告知当前节点的哪个邻居已经遍历(他的父节点在DFS遍历中)。

For example DFS in Python (undirected tree): 例如Python中的DFS(无向树):

def dfs(curr_node, parent):
    for node in getNeighbors(curr_node):
        if node!=parent:
            dfs(node)

BFS however, is done iteratively, and you can't avoid marking in the undirected case. 然而,BFS是迭代完成的,你无法避免在无向情况下进行标记。

This is a simple recursive way to do a DFS Algorithm: 这是一种简单的递归方式来执行DFS算法:

def dfs(node):
    """Depth First Search Algorithm"""
    if not node or node.visited:
        return

    node.visited = True

    dfs(node.below)
    dfs(node.right)
    dfs(node.above)
    dfs(node.left)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM