C# 中的反向广度优先遍历
有人有 C# 中反向广度优先遍历算法的现成实现吗?
通过反向广度优先遍历,我的意思是不是从公共节点开始搜索树,而是从底部搜索树并逐渐收敛到公共节点。
我们看下图,这是广度优先遍历的输出:
在我的反向广度优先遍历中,9
、10
、11
和12
将是前几个节点找到(它们的顺序并不重要,因为它们都是一阶)。 5
、6
、7
和 8
是找到的第二个节点,依此类推。 1
将是找到的最后一个节点。
有什么想法或指示吗?
编辑:将“广度优先搜索”更改为“广度优先遍历”以澄清问题
Anyone has a ready implementation of the Reverse Breadth First traversal algorithm in C#?
By Reverse Breadth First traversal , I mean instead of searching a tree starting from a common node, I want to search the tree from the bottom and gradually converged to a common node.
Let's see the below figure, this is the output of a Breadth First traversal :
In my reverse breadth first traversal , 9
,10
,11
and 12
will be the first few nodes found ( the order of them are not important as they are all first order). 5
, 6
, 7
and 8
are the second few nodes found, and so on. 1
would be the last node found.
Any ideas or pointers?
Edit: Change "Breadth First Search" to "Breadth First traversal" to clarify the question
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用堆栈和队列的组合。
使用队列执行“正常”BFS(我想您已经知道这样做),并在遇到节点时继续将节点推送到堆栈上。
一旦完成 BFS,堆栈将包含相反的 BFS 顺序。
Use a combination of a stack and queue.
Do the 'normal' BFS using the queue (which I presume you know to do already), and keep pushing nodes on the stack as you encounter them.
Once done with the BFS, the stack will contain the reverse BFS order.
从
rootNode
运行普通的BFS,并让深度[i]=深度为i的节点的链接列表
。因此,对于您的示例,您将拥有:深度[1] = {1},深度[2] = {2,3,4}等
。您可以通过简单的 BFS 搜索来构建它。然后打印深度[maxDepth]中的所有节点,然后打印深度[maxDepth - 1]中的节点,依此类推。节点
i
的深度为等于其父节点的深度+1。根节点的深度可以认为是1或0。Run a normal BFS from
rootNode
and letdepth[i] = linked list of nodes with depth i
. So for your example you'll have:depth[1] = {1}, depth[2] = {2, 3, 4} etc.
. You can build this with a simple BFS search. Then print all the nodes indepth[maxDepth]
, then those indepth[maxDepth - 1]
etc.The depth of a node
i
is equal to the depth of its father node + 1. The depth of the root node can be considered 1 or 0.