PTA-Complete Binary Search Tree

Data Structures and Algorithms (English)

7-7 Complete Binary Search Tree

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define Max 1000

int A[Max];
int T[Max];

int comp(const void*a, const void*b)//用来做比较的函数。
{
	return *(int*)a - *(int*)b;
}

/*
*@program 获得左子树的规模(利用完全二叉树的特性)
*@param n 母树的规模
*/
int getALeftLength(int n) {
	int depth = floor(log(n+1) / log(2));//母树的深度
	int x = n + 1 - pow(2, depth);
	x = (x < pow(2, depth - 1)) ? x : pow(2, depth - 1);
	return x + pow(2, depth-1)-1;
}

/*
*@program 核心算法
*@param ALeft 当前树最左端的下标
*@param ARight 当前树最右端的下标
*@param TRoot 树T根节点的下标
*/
void solve(int ALeft, int ARight, int TRoot) {
	int n = ARight - ALeft + 1;//为当前树的规模
	if (n == 0) return;

	int leftLength = getALeftLength(n);

	T[TRoot] = A[ALeft + leftLength];
	int TLeftRoot = TRoot * 2 + 1;
	int TRightRoot = TLeftRoot + 1;

	solve(ALeft, ALeft + leftLength - 1, TLeftRoot);
	solve(ALeft + leftLength + 1, ARight, TRightRoot);
}

int main() {
	int n, number;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &number);
		A[i] = number;
	}

	qsort(A, n, sizeof(int), comp);

	solve(0, n - 1, 0);

	for (int i = 0; i < n; i++) {
		printf("%d", T[i]);
		if (i != n - 1) {
			printf(" ");
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值