Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
Sample Input:
10
1 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
题意:给定一个序列,输出这个序列构成的完全二叉树的层序遍历。
既然是完全二叉树,那么优先填充左边的节点,其次因为是搜索树,左边的节点都会比根节点小,而右边的节点都会比根节点大,根据这个性质,就可以确定根节点的值了,然后递归,对左右子树也进行一样的处理,因为左右子树也是完全二叉搜索树,将结果保存在数组中,最后按序输出就是层序遍历了。不过首先要对输入的序列进行排序才行。这里假设输入的序列数组下标从1开始,存在in中,层序遍历结果存在ans数组中
以最开始的树为例,起始位置为1,结束位置为10。根节点的左子树中未满的那一层有3个节点,右子树中未满的那一层有0个节点,因此根节点的值为in[(1+3+10-0)/2]=in[7],将根节点数值存入ans[1]中
那么下一次就是处理根节点左右的序列了,分别为1-6和8-10,对应结果存入ans[2×1],ans[2×1+1]。
再以其中一颗子树为例,起始位置为5,结束位置为6,左子树中未满的那一层有1个节点,那么根节点的值为in[(5+1+6-0)/2],存入ans[5]中。可以验证这种方法对起始位置不是1的序列也是正确的。
#include <bits/stdc++.h>
using namespace std;
int ans[1005],in[1005],n;
void solve(int l,int r,int sub)
{
if(r<l)
return;
int nn=r-l+1;//表示当前子树的总节点数
int i=1;//表示一层满时的节点数
int ln,rn;//表示左右树未满的那一层的节点数
while(nn-i>=0)
{
nn-=i;
i<<=1;
}
i>>=1;
if(nn>i)//右子树未满的那一层上也有节点
{
ln=i;
rn=nn-i;
}
else//右子树未满的那一层为空
{
ln=nn;
rn=0;
}
int mid=(l+ln+r-rn)>>1;
ans[sub]=in[mid];
solve(l,mid-1,sub<<1);
solve(mid+1,r,(sub<<1)+1);
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>in[i];
}
sort(in+1,in+n+1);
solve(1,n,1);
for(int i=1;i<n;i++)
cout<<ans[i]<<" ";
cout<<ans[n];
return 0;
}