我有这个代码用于广度优先搜索:
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时获得一些帮助。
答案 0 :(得分:0)
简单的答案是..只需将队列更改为堆栈! (假设它是二叉树)
如果你想从左到右遍历你应该颠倒推动的顺序(就像我做的那样):
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 - &gt; B - &gt; D - &gt; E - &gt; C - &gt; F - &gt; ģ
操作顺序为:
使用递归有类似的方法(就像使用隐式堆栈一样)
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