本文介绍了非递归深度优先搜索算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种针对非二叉树的非递归深度优先搜索算法。
I am looking for a non-recursive depth first search algorithm for a non-binary tree. Any help is very much appreciated.
推荐答案
DFS:
list nodes_to_visit = {root};
while( nodes_to_visit isn't empty ) {
currentnode = nodes_to_visit.take_first();
nodes_to_visit.prepend( currentnode.children );
//do something
}
BFS:
list nodes_to_visit = {root};
while( nodes_to_visit isn't empty ) {
currentnode = nodes_to_visit.take_first();
nodes_to_visit.append( currentnode.children );
//do something
}
两者的对称性很酷。
更新:如前所述, take_first()
会删除并返回第一个列表中的元素。
Update: As pointed out, take_first()
removes and returns the first element in the list.
这篇关于非递归深度优先搜索算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!