多路树上的BFS遍历?

时间:2021-02-13 12:23:58

标签: tree binary-search-tree traversal breadth-first-search tree-traversal

我在 bfs 上看到过示例、代码和参考资料,但是,它们似乎都集中在遍历二叉树上。我想知道多路树是否可以进行bfs遍历,如果可以,我在哪里可以找到它的编码参考?

3 个答案:

答案 0 :(得分:1)

如果您清楚地了解 BFS 的工作原理,那么无论您处理的是哪种树(或者更具体地说是 graph),您总能找到方法。

如果你真的不清楚如何在多节点树中进行 BFS,这里是我的伪代码:

     Queue queue; // a de-queue typed data-structure.
     queue.add(root); // root of the tree.

     while -> queue is not empty() :  // traversed untill queue become empty

          tempNode := queue.peek();   // process the peeked item from queue
              queue.pop();

          process -> tempNode.item;

          while -> tempNode.childnode is not null:
                   queue.add(tempNode.childnode)
                   tempNode := tempNode.childnode;

          end of while;

     end of while;

答案 1 :(得分:0)

确实,我也搜索过,bfs 并不专注于多路树。 但是,使用 graph exists 引用 bfs。因为多路树是图的一个子集,你可能会在那里找到你的快乐。

答案 2 :(得分:0)

BFS 确实是一种遍历,并不特定于 二叉 树,但可以用于任何图。维基百科在 Breadth-first search 上有一个条目,它甚至提供了旨在处理任何图形的伪代码。

<块引用>

输入:图 G 和 G 的起始顶点根

输出:目标状态。父链接追踪返回到的最短路径 根

 1  procedure BFS(G, root) is
 2      let Q be a queue
 3      label root as discovered
 4      Q.enqueue(root)
 5      while Q is not empty do
 6          v := Q.dequeue()
 7          if v is the goal then
 8              return v
 9          for all edges from v to w in G.adjacentEdges(v) do
10              if w is not labeled as discovered then
11                  label w as discovered
12                  Q.enqueue(w)