# 04-树6 Complete Binary Search Tree (30分)

75人阅读 评论(0)

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  (\le 1000). Then  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 Output:

6 3 8 1 5 7 9 0 2 4

### 思路:

#include <algorithm>
using namespace std;

sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址

int cmp( const int &a, const int &b )
{
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);//对数组a降序排序

#include <iostream>
#include <algorithm>

using namespace std;

int a[1000];//存储输入的数据
int b[1000];//存储输出的数据
int len=0;

void trans(int a[],int b[],int n,int root)
{

if(root*2<=n)	//如果有左孩子
trans(a,b,n,root*2);

b[root]=a[len++];	//中序遍历数组a，将a的结点按遍历顺序放在数组b中

if(root*2+1<=n)	//如果有右孩子
trans(a,b,n,root*2+1);

}

int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];		//输入键值，存放在数组a中
}
sort(a,a+n);	//把数组a的第0到n-1的元素排序
trans(a,b,n,1);
for(int i=1;i<=n-1;i++)
{
cout<<b[i]<<" ";
}
cout<<b[n];
return 0;
} 

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：3414次
• 积分：254
• 等级：
• 排名：千里之外
• 原创：23篇
• 转载：1篇
• 译文：0篇
• 评论：0条
文章分类
阅读排行