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
我的答案:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define MaxSize 1005
int sortNum[MaxSize] = {0};
int CBTreeNode[MaxSize] = {0};
int countNum = 0;
void CreatCBTree(int root,int N)
{
if(root > N)
return;
int left = root * 2;
int right = root * 2 + 1;
CreatCBTree(left,N); //中序遍历LGR从小到大 小的先
CBTreeNode[root] = sortNum[countNum++];
CreatCBTree(right,N);
}
int main()
{
int N;
scanf("%d",&N);
for(int i = 0; i < N; i++)
scanf("%d",&sortNum[i]);
sort(sortNum,sortNum + N);//按从小到大排序
CreatCBTree(1,N);
for(int i = 1; i <= N; i++) {
if(i != N)
printf("%d ",CBTreeNode[i]);
else
printf("%d",CBTreeNode[i]);
}
return 0;
}
感悟
好难,我现在也没想明白
中序的中序就是层序的下标?为啥?