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
二叉查找树(BST)被递归地定义为二叉树,该二叉树具有以下属性:
- 节点的左子树只包含键小于该节点键的节点。
- 节点右边的子树只包含键大于或等于节点键的节点。
- 左右子树也必须是二分搜索法树。
完全二叉树(CBT)是一种完全填充的树,可能除了底层是从左到右填充的。
现在给定一系列不同的非负整数键,如果要求树也必须是CBT,则可以构造唯一的BST。你应该输出这个BST的层次顺序遍历序列。
输入规格:
每个输入文件包含一个测试用例。对于每种情况,第一行包含一个正整数N (≤1000).然后N下一行给出了不同的非负整数键。一行中的所有数字由空格分隔,并且不大于2000。
输出规格:
对于每个测试用例,在一行中打印相应的完整二叉查找树的层次顺序遍历序列。一行中的所有数字必须用空格隔开,并且行尾不能有多余的空格。
思路:
将读入的n个数排序,然后计算当前根的左子树和右子树分别有多少节点,在当前[l,r]区间中,左子树是[l,l+lt-1],右子树是[r-rt+1,r],lt、rt是左、右子树节点数,根为mid = l+lt = r-rt。
#include <bits/stdc++.h>
using namespace std;
int n,flag = 0;
int a[1005];
int h[11] = {0,1,3,7,15,31,63,127,255,511,1023};
queue<int>q;
int f(int l,int r){
if(l == r)return l;
else{
int cnt = 1;
for(int i = 1;i<11;i++){
if(r-l+1==h[i]){//求当前树的层高
cnt = i;
break;
}else if(r-l+1>h[i]){
cnt++;
}else break;
}
int len = r-l+1 - h[cnt-1];//求最下面一层的节点数
int llen,rlen; //最下面一层节点中属于左子树的数量和属于右子树的数量
if(len<=h[cnt-2]+1){
llen = len;
rlen = 0;
}else{
llen = h[cnt-2]+1;
rlen = len - llen;
}
int lt = llen + (r-l-len)/2; //求得左右子树的节点个树
int rt = rlen + (r-l-len)/2;
int mid = l + lt;
if(mid-1>=l){
q.push(l);
q.push(mid-1);
}
if(r>=mid+1){
q.push(mid+1);
q.push(r);
}
return mid;
}
}
int main()
{
cin>>n;
for(int i = 1;i<=n;i++){
cin>>a[i];
}
sort(a+1,a+1+n);
q.push(1);
q.push(n);
while(!q.empty()){
int l,r;
l = q.front();
q.pop();
r = q.front();
q.pop();
int mid = f(l,r);
if(flag)cout<<" ";
else flag = 1;
cout<<a[mid];
}
return 0;
}