A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
- Both the left and right subtrees must also be binary search trees.
A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.
Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.
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
思路
这题题目意思很简单,就是给出一串序列,让你创建一棵CBT(就是BST+完全二叉树),那么我们就可以利用BST和完全二叉树的特性啦~
①利用BST的特性:BST的中序序列是一个递增序列,但是题目给的序列不一定递增(不要被样例给骗了),但是没关系,用sort函数排个序就好了;
②利用完全二叉树的特性:完全二叉树除了底层其他都是满结点的状态,因此,完全可以用一个数组来存储这棵树,这样的话,下标就是结点标号(注意,是结点标号,不是数据,题目给的是data域,也就是说应该是数组某个下标的值),而且根结点的下标就是1。
于是,我们就先把输入的序列进行从小到大排序,然后就得到了中序序列。再对CBT进行中序遍历(这时候CBT是一棵内容为空的树,也就是没有数据域,但是下标(结点编号)还是严格按照完全二叉树来排的,所以可以认为此时的CBT确实存在,但是没有数据域),每次访问根的时候,就把中序序列的一个值赋给它。这里要注意的是,边界条件是当root>N(N为结点个数)时,因为我们访问的总是数组的下标(相当于地址),而N个结点构成的完全二叉树的话,下标编号就是从1~N。
中序遍历完之后,CBT就彻底建立好了。至于完全二叉树的层序的话,数组按正序输出就是层序遍历的序列。
代码
#include<cstdio>
#include<stdlib.h>
#include<algorithm>
#include<queue>
#include<string.h>
#include<iostream>
using namespace std;
const int maxn = 1010;
int Data[maxn] = {0};
int CBT[maxn] = {0};
int index = 0;
void inorder(int root, int N){
if(root>N) return;//这里返回的条件是当下标超过结点数N
inorder(root*2, N);
CBT[root] = Data[index++];
inorder(root*2+1, N);
}
int main(){
int N;
scanf("%d", &N);
for(int i=0;i<N;i++) scanf("%d", &Data[i]);
sort(Data, Data+N);
inorder(1, N);//根结点是1
for(int i=1;i<=N;i++){
if(i==1) printf("%d", CBT[i]);
else printf(" %d", CBT[i]);
}
return 0;
}