【发布时间】:2020-06-28 18:25:17
【问题描述】:
这是我最近遇到的面试问题之一。
给定一棵完全或几乎完全二叉树的根地址,我们必须编写一个函数将二叉树转换为最大堆。
这里不涉及数组。树已经构建好了。
例如,
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;
}
【问题讨论】:
-
您展示的“二叉树”是最小堆,而不是排序二叉树。这是你的意图吗?
-
@Sneftel 你好!它恰好是一个最小堆。它不是故意的,可以是任何随机完整或几乎完整的二叉树。
-
"不涉及数组" - 这是否意味着您不允许将树复制到数组然后堆化,或者这是否意味着您最初没有将树作为数组?如果是后者,复制到数组,堆化,重建树;这是 O(n)。
-
@G.Bach 是的,您不允许将树复制到数组然后堆化,是的,您最初没有将树作为数组。它是一个二叉树,而不是数组的二叉树可视化。
标签: algorithm data-structures heap binary-tree binary-heap