最小堆 php,在数组最小堆中查找小于x的所有键

树最小堆有一个简单的递归算法:

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);

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值