写在前面

  • 思路分析
  • 给你1个序列,所有的数都非负且不同,用这个序列建一个完全二叉搜索树,再给出这个树的层序序列
  • 解题思路:
  • 二叉搜索树的中序序列是有序的,那么我们把输入的序列进行排序,得到这棵BST的中序序列
  • 再按中序遍历的方式建树,得到这棵完全二叉搜索树
  • 因为是完全二叉树,所以可以用一个数组来保存,且有n个结点,一定会把前面n个空间占满。
  • 输出层序序列
  • 热点知识,参考代码易理解

测试用例

input:
10
1 2 3 4 5 6 7 8 9 0
output:
6 3 8 1 5 7 9 0 2 4

ac代码

#include<iostream>
#include<cstdio>
#include<string>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=1010;
int num[maxn],cbt[maxn],n,inx=0;

void inorder(int root)
{
if(root>n)
return;
inorder(2*root);
cbt[root]=num[inx++];
inorder(2*root+1);
}

int main()
{
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;
}