2022.1.28 练习 PAT甲 1064 Complete Binary Search Tree (原题链接)
妙啊,自己想的好麻烦,一看算法笔记上的题解,佩服佩服,我的脑袋怎么这么不转弯。。。
思想:
步骤1: 如果使用数组来存放完全二叉树,那么对完全二叉树当中的任何一个结点(设编号为x,其根结点编号为1),其左孩子结点的编号为2x,右孩子结点的编号为2x+1。那么就可以开一个数组CBT[MAX_SIZE],其中CBT[1]~CBT[n]按层序存放完全二叉树的n个结点。
步骤2: 考虑到对一颗二叉排序树来说,其中序遍历序列时递增的,因此先将输入的数字从小到大排序,然后对CBT数组表示的二叉树进行中序遍历,并在遍历过程中将数字从小到大填入数组,最后就能得到一颗完全二叉排序树。CBT数组本身就是按照二叉树的层序存放结点的,因此直接遍历输出即得到结果。
注意点: 代码中设置了一个变量为indexx
,因为#include <bits/stdc++.h>
头文件中有一个函数叫index
,避免重名。(如果变量名为index
的话报错T T)
题解如下:
#include <bits/stdc++.h>
using namespace std;
const int MAX_SIZE=1010;
int n;
int indexx=0;
int CBT[MAX_SIZE];
int num[MAX_SIZE];
void inorder(int root)
{
if(root>n)
return;
inorder(root*2);
CBT[root]=num[indexx++];
inorder(root*2+1);
}
int main()
{
std::ios::sync_with_stdio(false);
cin>>n;
for(int i=0;i<n;i++)
{
cin>>num[i];
}
sort(num,num+n);
inorder(1);
for(int i=1;i<=n;i++)
{
cout<<CBT[i];
if(i<n)
cout<<" ";
}
return 0;
}