There is a simple recursive algorithm for a mini-heap tree:
void smaller_than(Node *node, int x)
{
if (node->value >= 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);
}
If the root of the subtree has a value greater than or equal to x, then, by the definition of a mini-heap, all its descendants will also have values greater than or equal to x. The algorithm should not investigate deeper than objects crossing it; therefore, it is O (k).
Of course, this is a trivial thing translating this into an array algorithm:
#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)
{
if (pos >= count)
return;
if (heap[pos] >= x)
{
return;
}
printf("%d\n", heap[pos]);
smaller_than(x, LEFT(pos), heap, count);
smaller_than(x, RIGHT(pos), heap, count);
}
source
share