【问题标题】:Depth first search code snippet深度优先搜索代码片段
【发布时间】:2013-12-11 22:07:46
【问题描述】:

我有此代码用于广度优先搜索:

var queue = new Queue<BinaryNode>();
queue.Enqueue(rootNode);

while(queue.Any())
{
  var currentNode = queue.Dequeue();
  if(currentNode.data == searchedData)
  {
    break;
  }

  if(currentNode.Left != null)
    queue.Enqueue(currentNode.Left);

  if(currentNode.Right != null)
    queue.Enqueue(currentNode.Right);
}

现在我正在尝试对深度优先搜索执行相同的操作,并且我知道 DFS 使用堆栈而不是队列,所以我可以在编写 DFS 时获得一些帮助。

【问题讨论】:

  • 只需将队列更改为堆栈即可:P.
  • @Marco 你是认真的吗?就这么简单?
  • Push 代替入队,Pop 代替出队?
  • 是的,就是这么简单。看看我的回答:P

标签: depth-first-search


【解决方案1】:

简单的答案是......只需将队列更改为堆栈! (假设是二叉树)

如果你想从左到右遍历,你应该颠倒推送的顺序(就像我一样):

stack.push(rootNode);

while(stack.Any()) {
  var currentNode = stack.pop();
  if(currentNode.data == searchedData)
    break;

  if(currentNode.Right != null)
    stack.push(currentNode.Right);

  if(currentNode.Left != null)
    stack.push(currentNode.Left);

}

所以..这将遍历树:

按顺序:

A -> B -> D -> E -> C -> F -> G

操作顺序为:

  1. 推(a)
  2. 流行;一个
  3. 推(c)
  4. 推(b)
  5. 流行; b
  6. 推(e)
  7. 推(d)
  8. 流行; d
  9. 流行; e
  10. 流行; c
  11. 推(g)
  12. 推(f)
  13. 流行音乐
  14. 流行音乐

另一种方式

使用递归也有类似的方法(就像使用隐式堆栈一样)

def dfsSearch(node, searchedData):
    # Base case 1: end of the tree
    if node == None: return None  

    # Base case 2: data found
    if node.data == searchedData: return node 

    # Recursive step1: Traverse left child
    left = dfsSearch(node.left, searchedData)
    if left != None: return left

    # Recursive step2: Traverse right child
    right = dfsSearch(node.right, searchedData)
    if right != None: return right

    return None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多