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
首先对输入序列进行排序
0 1 2 3 4 5 6 7 8 9
可以排成这样的完全二叉树
0
1 2
3 4 5 6
7 8 9
将其改为完全平衡二叉树
6
3 7
1 5 8 9
0 4 2
所以就是递归左子树的结点数
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 1000;
int a[N],Tree[N];
int GetHeight(int n)/*求n个结点的总层数*/
{
int cnt = 0;
while(n)
{
cnt++;
n /= 2;
}
return cnt;
}
int GetSum(int h)/*求高度为h的树的总结点树*/
{
if(h < 1) return 0;
int sum = 1;
for(int i = 0; i < h ; i++)
{
sum *= 2;
}
return --sum;
}
int GetLevelSum(int h)/*求第h层的总结点数*/
{
if(h < 1) return 0;
int sum = 1;
for(int i = 0 ; i < h - 1; i++)
{
sum *= 2;
}
return sum;
}
int GetLeftHeight(int n)
{
int l = 0;
int h = GetHeight(n);/*求n个结点的总层数*/
l += GetSum(h - 2);
int x = n - GetSum(h - 1);
int x1 = GetLevelSum(h);
if(x < x1 / 2)
{
l += x;
}
else
{
l += x1 / 2;
}
return l;
}
void solve(int ALeft/*当前左子树根结点位置*/,int ARight/*当前右子树根结点位置*/,int root/*当前根结点*/)
{
int n = ARight - ALeft + 1;/*当前的结点总数*/
if(n == 0)
{
return;
}
int l = GetLeftHeight(n);/*得到当前树左子树的高度*/
Tree[root] = a[ALeft + l];
int LeftRoot = 2 * root + 1;/*左子树的根结点位置*/
int RightRoot = LeftRoot + 1;/*右子树根结点位置*/
solve(ALeft,ALeft + l - 1,LeftRoot);/*递归遍历左子树*/
solve(ALeft + l + 1,ARight,RightRoot);/*递归遍历右子树*/
}
int main()
{
int n;
cin >> n;
for(int i = 0 ; i < n ; i++)
{
cin >> a[i];
}
sort(a,a + n);
solve(0,n - 1,0);
cout << Tree[0];
for(int i = 1 ; i < n ; i++)
{
cout << " " << Tree[i];
}
return 0;
}