- Complete Binary Search Tree (30)
时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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
题意浓缩:已知完全二叉树的中序遍历(排序后结果),求其层次遍历。
难点在于根节点的寻找,刚开始没考虑周全,浪费了半小时,后来发现错误后,分分钟搞定。代码也比较简单。
可是只拿了28分,没找到有什么问题,猜测可能是寻找根节点算法会在某种情况下出错,但是改了改还是扣分,郁闷。
看了晴神的代码,十分灵巧简便。利用中序遍历本身的性质,反过来建立层级遍历。
晴神代码:
#include <iostream>
#include <algorithm>
using namespace std;
int n,a[1010],CBT[1010],index=0;
void inorder(int root){
if(root>n) return ;
inorder(root*2);
CBT[root]=a[index++];
inorder(root*2+1);
}
int main(){
freopen("in.txt","r",stdin);
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
inorder(1);
cout<<CBT[1];
for(int i=2;i<=n;i++)
cout<<" "<<CBT[i];
return 0;
}
我的代码:
#include <iostream>
#include <algorithm>
using namespace std;
int n,a[1010],CBT[1010];
int findroot(int start,int end)//寻找该段数字中的根节点,该段数字范围为[start,end].
{
int rnum=0,lnum=0,s=1;//lnum,rnum分别为左右子树的节点数。s为当前所在层最大容量,第一层为1,第二层为2.以此类推。
while(rnum+lnum<end-start){//先存满左子树结点,再接着存满右子树结点。
if(lnum<s)
lnum++;
else if(rnum<s)
rnum++;
else{
s=s+s*2;//存满一层后,接着存下一层。
}
}
return lnum+start;//返回根节点的值,即(左端点+左子树节点数)
}
void getCBT(int adr,int start,int end)//adr是CBT的地址,start,end是数字段范围
{
if(adr>n){
return;
}
else{
int root=findroot(start,end);
CBT[adr]=a[root];
getCBT(adr*2,start,root-1);
getCBT(adr*2+1,root+1,end);
}
}
int main(){
freopen("in.txt","r",stdin);
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
getCBT(1,0,n-1);
cout<<CBT[1];
for(int i=2;i<=n;i++)
cout<<" "<<CBT[i];
return 0;
}