A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
1.The left subtree of a node contains only nodes with keys less than the node’s key.
2.The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
3.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
评价: 此题比较有意思,给出了二叉搜索树和完全二叉树的定义来唯一确定一个数。
首先的一个问题是我们用什么方法来建树?不是静态链表或者动态链表,因为有了完全二叉树的定义,我们默认root为1。那么我的思路是怎么确定每个节点的数据域呢?又因为需要满足BST的性质,我需要知道每个节点左子树的大小。假设输入数据已经从小到大排过序。那么根据子树的size,我们就可以确定当前点的data。难度不大。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
int a[1005];
int tree[1005];
int size[1005];
int n;
void findSize(int root)
{
int l=root<<1;
if(l<=n)
{
findSize(l);
size[root]+=size[l];
}
if(l+1<=n)
{
findSize(l+1);
size[root]+=size[l+1];
}
size[root]++;
}
void fillData(int root,int l,int r)
{
int lRoot=root<<1;
if(lRoot<=n)
{
tree[root]=a[l+size[lRoot]];
fillData(lRoot,l,l+size[lRoot]-1);
}
else
{
tree[root]=a[l];//说明到了叶子节点
return ;
}
int rRoot=lRoot+1;
if(rRoot<=n)
fillData(rRoot,l+size[lRoot]+1,r);
}
int num=0;
void level()
{
queue<int> que;
que.push(1);
while(!que.empty())
{
int now=que.front();
que.pop();
a[num++]=tree[now];
int l=now<<1;
if(l<=n)
que.push(l);
if(l+1<=n)
que.push(l+1);
}
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+1+n);
findSize(1);
fillData(1,1,n);
level();
for(int i=0;i<n-1;i++)
cout<<a[i]<<" ";
cout<<a[n-1];
return 0;
}