我认为我知道答案并且最小复杂度是O(nlogn).
但是有什么方法可以让我从堆中创建二叉搜索树O(n)复杂?
没有算法可以在 O(n) 时间内从堆构建 BST。原因是给定 n 个元素,您可以在 O(n) 时间内从它们构建一个堆。如果您有一组值的 BST,则可以通过中序遍历在 O(n) 时间内对它们进行排序。如果您可以在 O(n) 时间内从堆构建 BST,那么您就可以通过以下方式获得 O(n) 排序算法:
- 在 O(n) 时间内构建堆,
- 在 O(n) 时间内将堆转换为 BST,并且
- 在 O(n) 时间内遍历 BST 以获得排序序列。
因此,不可能在 O(n) 时间内(或 o(n log n) 时间内将堆转换为 BST,其中 o 是小 O 表示法).
However, it is possible to build a BST from a heap in O(n log n) time by repeatedly dequeueing the maximum value from the BST and inserting it as the rightmost node in the tree. (You'd need to store a pointer there for fast access; just inserting at the root repeatly would take O(n2) time.)
希望这可以帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)