其他分享
首页 > 其他分享> > [PAT-A 1064]Complete Binary Search Tree (30 分)

[PAT-A 1064]Complete Binary Search Tree (30 分)

作者:互联网

在这里插入图片描述
考察二叉排序树

题目大意:给出N个非负整数,要用它们构建一颗完全二叉排序树,输出这颗完全二叉树的层序遍历序列

1.使用数组来存放完全二叉树,完全二叉树中的任何一个节点(设编号为x,其中根节点编号为1),其左孩子节点编号为2x,右孩子节点编号为2x+1,可以开一个数组CBT[MAXN],其中1-N按层序存放完全二叉树的n个节点
2.对于一颗二叉排序树来说,其中中序遍历是递增的,先将数字从小到达排序,然后对CBT数组表示的二叉树进行中序遍历,并在遍历的进程中将数字从小到大填入数组,最后就能得到一颗完全二叉树,而由于CBT数组就是按照二叉树层序来存放节点的,因此只需要将数组元素按顺序输出即为层序遍历序列

AC代码:

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1010;
int n, number[maxn], CBT[maxn], index = 0;
void inOrder(int root) {
	if (root > n)return;
	inOrder(root * 2);
	CBT[root] = number[index++];
	inOrder(root * 2 + 1);
}
int main() {
	(void)scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		(void)scanf("%d", &number[i]);
	}
	sort(number, number + n);
	inOrder(1);
	for (int i = 1; i <= n; i++) {
		printf("%d", CBT[i]);
		if (i < n)printf(" ");
	}
	return 0;
}	

标签:Binary,Search,PAT,int,number,二叉树,CBT,root,节点
来源: https://blog.csdn.net/weixin_44699689/article/details/100573113