非递归深度优先搜索算法递归、算法、深度

2023-09-10 22:50:54 作者:我很好好到只能凑热闹

我要寻找一个非二叉树非递归深度优先搜索算法。任何帮助是非常AP preciated。

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.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.first();
  nodes_to_visit.append( currentnode.children );
  //do something
}

两者的对称性是相当凉爽。

The symmetry of the two is quite cool.

更新:作为指出,第()删除并返回列表中的第一个元素

Update: As pointed out, first() removes and returns the first element in the list.

 
精彩推荐
图片推荐