这是我最近遇到的一道面试题。
给定完整或几乎完整二叉树的根地址,我们必须编写一个将树转换为最大堆的函数。
这里没有涉及任何数组。树已经构建好了。
例如,
1
/ \
2 5
/ \ / \
3 4 6 7
输出结果可以是任意可能的最大堆--
7
/ \
3 6
/ \ / \
2 1 4 5
或 7
/ \
4 6
/ \ / \
2 3 1 5
我写了一个解决方案,但是使用先序遍历和后序遍历的组合,但我猜测它的运行时间是O(n^2)。我的代码输出如下:
7
/ \
3 6
/ \ / \
1 2 4 5
我正在寻找更好的解决方案。请问有人可以帮忙吗?
编辑:
我的代码
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;
}