Converting a heap to a BST in O(n) time?
Asked Answered
T

1

9

I think that I know the answer and the minimum complexity is O(nlogn).

But is there any way that I can make an binary search tree from a heap in O(n) complexity?

Translator answered 31/12, 2012 at 23:37 Comment(1)
make BST from Heap in O(n) is MORE efficient then O(nlogn).Translator
B
22

There is no algorithm for building a BST from a heap in O(n) time. The reason for this is that given n elements, you can build a heap from them in O(n) time. If you have a BST for a set of values, you can sort them in O(n) time by doing an inorder traversal. If you could build a BST from a heap in O(n) time, you could then have an O(n) sorting algorithm by

  1. Building the heap in O(n) time,
  2. Converting the heap to a BST in O(n) time, and
  3. Walking the BST in O(n) time to get a sorted sequence.

Therefore, it is not possible to convert a heap to a BST in O(n) time (or in o(n log n) time, where o is little-o notation).

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.)

Hope this helps!

Bordello answered 1/1, 2013 at 1:55 Comment(2)
Thank you! it helped me very much!Translator
Thanks! Helped me too :)Nesto

© 2022 - 2025 — McMap. All rights reserved.