Reverse Breadth First traversal in C#

浪尽此生 提交于 2019-12-02 22:43:20

Run a normal BFS from rootNode and let depth[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 in depth[maxDepth], then those in depth[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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!