找出堆中小于某个值X的所有节点

本文提供了《数据结构与算法分析——c语言描述》一书中关于堆的练习题解答,包括d堆、左式堆和二项队列的实现细节及打印小于给定值X的所有元素的算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《数据结构与算法分析——c语言描述》 练习6.9 a,b 答案


d堆的,D换成2就是二叉堆的了


static void printLessThanX_internal(ElementType X, PriorityQueue h,int pos) {
	if (pos >= 1 && pos <= h->capacity) {
		if (h->elements[pos] < X) {
			printf("%d ", h->elements[pos]);
			int firstChild = firstSonCursor(pos);
			for (int i = 0; i < D; i++)
				printLessThanX_internal(X, h, firstChild + i);
		}
	}
}

void printLessThanX(ElementType X, PriorityQueue h) {
	printLessThanX_internal(X, h, 1);
}


左式堆

void printLessThanX(ElementType X, PriorityQueue h) {
	if (h) {
		if (h->element < X) {
			printf("%d ", h->element);
			printLessThanX(X, h->left);
			printLessThanX(X, h->right);
		}
	}
}


二项队列

void printLessThanX_internal(ElementType X, Position p) {
	if (p) {
		if (p->element < X) {
			printf("%d ", p->element);
			printLessThanX_internal(X, p->leftChild);
		}
		printLessThanX_internal(X, p->nextSibling);//各二项树大小没有关系
	}
}

void printLessThanX(ElementType X, BinQueue h) {
	for (int i = 0, j = 1; j <= h->currentSize; i++, j *= 2) {
		if (h->theTrees[i]&&h->theTrees[i]->element < X) {//有些指针是空
			printf("%d ", h->theTrees[i]->element);
			printLessThanX_internal(X,h->theTrees[i]->leftChild);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值