Max-Heapify二叉树

dis*_*kit 11 algorithm heap binary-tree binary-heap data-structures

这是我最近遇到的面试问题之一.

给定完整或几乎完整的二叉树的根地址,我们必须编写一个函数将树转换为最大堆.

这里没有涉及数组.树已经建成了.

例如,

              1   
         /         \
        2           5
      /   \       /   \ 
     3      4    6     7
Run Code Online (Sandbox Code Playgroud)

可以有任何可能的最大堆作为输出 -

              7   
         /         \
        3           6
      /   \       /   \ 
     2     1     4     5
Run Code Online (Sandbox Code Playgroud)

要么

              7   
         /         \
        4           6
      /   \       /   \ 
     2     3     1     5
Run Code Online (Sandbox Code Playgroud)

等等...

我写了一个解决方案,但使用了前后顺序遍历的组合,但我想在O(n ^ 2)中运行.我的代码提供了以下输出.

              7   
         /         \
        3           6
      /   \       /   \ 
     1     2     4     5
Run Code Online (Sandbox Code Playgroud)

我一直在寻找更好的解决方案.有人可以帮忙吗?

编辑:

我的守则

void preorder(struct node* root)
{    
    if(root==NULL)return;
    max_heapify(root,NULL);
    preorder(root->left); 
    preorder(root->right);
}
void max_heapify(struct node* root,struct node* prev)
{
    if(root==NULL)
        return ;             
    max_heapify(root->left,root);
    max_heapify(root->right,root);
    if(prev!=NULL && root->data > prev->data)
    {
        swapper(root,prev);
    }     
}
void swapper(struct node* node1, struct node* node2)
{   
    int temp= node1->data;
    node1->data = node2->data;
    node2->data = temp;
}
Run Code Online (Sandbox Code Playgroud)

Abh*_*sal 5

我认为这可以通过以下程序在O(NlogN)时间内完成. http://www.cs.rit.edu/~rpj/courses/bic2/studios/studio1/studio121.html

假设树中有一个元素,其左右子树都是堆.

          E
       H1   H2
Run Code Online (Sandbox Code Playgroud)

由E,H1和H2形成的树可以通过使元素E向下游到其正确位置而在logN时间内堆积.

因此,我们开始自下而上构建堆.转到最左边的子树,并通过简单的比较将其转换为堆.这也是为了它的兄弟姐妹.然后上去将其转换为堆.

同样地为每个元素做这件事.

编辑:正如评论中所提到的,复杂性实际上是O(N).

  • 我认为这里的复杂性分析是关闭的.如果你根据树的高度H来考虑,你会得到O(H)= 2*O(H-1)+ H,来自(1)堆积两个子树,以及(2)将根冒泡到它的位置.这表明O(H)= 2 ^ H,因此O(N)= N. (3认同)