【发布时间】: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