Max-Heapify A Binary Tree

后端 未结 4 487
半阙折子戏
半阙折子戏 2020-12-31 11:43

This is one of the interview questions I recently came across.

Given the root address of a complete or almost complete binary tree, we have to write a function to c

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 12:04

    I think this can be done in O(NlogN) time by the following procedure. http://www.cs.rit.edu/~rpj/courses/bic2/studios/studio1/studio121.html

    Assume there is an element in the tree whose both left and right sub-trees are heaps.

              E
           H1   H2
    

    This Tree formed by E, H1 and H2 can be heapified in logN time by making the element E swim down to its correct position.

    Hence, we start building the heap bottom up. Goto the left-most sub-tree and convert it to a heap by trivial comparison. Do this for it's sibling as well. Then go up and convert it to heap.

    Like-wise do this for every element.

    EDIT: As mentioned in the comments, the complexity is actually O(N).

提交回复
热议问题