有没有办法从DFS输出到BFS输出?
我一直在努力解决以下问题:我有一个DFS输出列表: [0.2500000074505806, 0.65000059604645, 0.15000000223517418, 0.450000298023224, 0.450000298023224, 0.849999940395355, 0.1500002223517418] 并希望将其转换为BFS订购,而无需先创建树,然后再应用BFS。作为参考,这是一个完整的二进制图,带有深度2。
感谢提前的帮助。
I have been struggling with the following problem: I have a DFS outputted list:
[0.2500000074505806,
0.6500000059604645,
0.15000000223517418,
0.45000000298023224,
0.45000000298023224,
0.8499999940395355,
0.15000000223517418]
and want to transform this to a BFS ordering without first creating a tree and then applying BFS. For reference, this is a complete binary graph with depth 2.
Thanks in advance for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于一般图,DFS不包含足够的信息来获得BFS输出。但是,如果您确定该图是7个节点上的完整二进制树,并且您可以从根而来dfs,输出为x1,x2,x3,…,x7,那么bfs输出将为x1,x2,x5,x3,x3 ,x4,x6,x7。
更一般而言,如果您在n个节点上具有完整的二进制树的DFS输出,则可以通过以下算法生成BFS输出的置换:
输出:输出:
该算法将DFS序列作为输入,并打印出根节点,即根节点,,并将其打印出根节点,即然后对FIFO队列中的每个sublist进行以下操作:打印左子女,然后将约一半的元素作为sublist添加到队列中,然后打印正确的孩子,然后将大约一半的元素添加为sublist 。
For general graphs, DFS doesn’t contain enough information to obtain the BFS output. But if you’re sure the graph is a complete binary tree on 7 nodes, and you ran DFS from the root and output is x1,x2,x3,…,x7, then the BFS output would be x1,x2,x5,x3,x4,x6,x7.
More generally, if you have the DFS output for a complete binary tree on n nodes, the permutation that gives the BFS output can be generated by the following algorithm:
Output:
The algorithm takes as input the DFS sequence, and prints the root node, then does the following for each sublist in the FIFO queue: prints the left child, then adds about half of the elements as a sublist to a queue, then prints the right child, then adds about half of the elements as a sublist to a queue.
当树被保证为完美的二进制树树全部都在底层,然后您可以使用务实的方法在其中填充级别顺序遍历的级别作为单独的列表,然后返回这些值的串联:
示例完美树:
示例为该树运行:
When the tree is guaranteed to be a perfect binary tree, i.e. where the leaves of the tree are all on the bottom level, then you could use a pragmatic approach where you populate the levels of the level order traversal as separate lists, and then return the concatenation of those values:
Example perfect tree:
Example run for that tree: