树最小堆有一个简单的递归算法:
void smaller_than(Node *node, int x)
{
if (node->value >= x)
{
/* Skip this node and its descendants, as they are all >= x . */
return;
}
printf("%d\n", node->value);
if (node->left != NULL)
smaller_than(node->left, x);
if (node->right != NULL)
smaller_than(node->right, x);
}
如果子树根的值大于或等于X,那么根据min堆的定义,其所有子代的值也将大于或等于X。该算法不需要比其遍历的项更深入地探索,因此它是O(k)。
当然,将其转换为数组算法是一件小事:
#define ROOT 0
#define LEFT(pos) ((pos)*2 + 1)
#define RIGHT(pos) ((pos)*2 + 2)
void smaller_than(int x, int pos, int heap[], int count)
{
/* Make sure item exists */
if (pos >= count)
return;
if (heap[pos] >= x)
{
/* Skip this node and its descendants, as they are all >= x . */
return;
}
printf("%d\n", heap[pos]);
smaller_than(x, LEFT(pos), heap, count);
smaller_than(x, RIGHT(pos), heap, count);
}
2万+

被折叠的 条评论
为什么被折叠?



