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 0Sample Output:
6 3 8 1 5 7 9 0 2 4
思路:一般想到的是先构建树,然后再遍历,因为是Complete Binary Tree (CBT)的缘故,它的节点排列有规律,就没有用构建树实现
大概思想:先排序;再找出此树中最大满二叉树以外的叶子节点;再层次遍历满二叉树(总有序数列的中间开始向外扩散)
AC才能考代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <math.h>
#include <queue>
using namespace std;
vector<int> leaf; //除满二叉树以外的叶子节点
vector<int> arr; //节点记录
int N;
int main()
{
cin>>N;
arr.resize(N);
for(int i=0;i<N;i++){
cin>>arr[i];
}
if(N==1){
cout<<arr[0];
return 0;
}
sort(arr.begin(),arr.end());
double ex = floor(log(N)/log(2)); //分离出的满二叉树的高度
int leafNum = N - pow(2,ex)+1; //除满二叉树以外的叶子节点的个数
int index = 0;
for(int i=0;i<leafNum;i++){ //满二叉树以外的叶子节点相邻之间应该相差一个节点,在有序数组中
leaf.push_back(arr[index]);
index += 2;
}
index = 0;
for(vector<int>::iterator it=arr.begin();it!=arr.end();it++){ //从arr中除去非满二叉树的节点
if(index==leafNum){
break;
}
if((*it)==leaf[index]){
arr.erase(it);
index++;
}
}
//模拟满二叉树的层次遍历,需用到队列
int mid = arr.size()/2;
int loc = mid+1;
queue<int> qu;
qu.push(mid);
int totalCount = 0;
int door = N-leafNum;
while(!qu.empty()){
int queueSize = qu.size();
for(int k=0;k<queueSize;k++){
int temp = qu.front();
qu.pop();
cout<<arr[temp]<<" ";
if(totalCount<door-1){
qu.push(temp-loc/2);
qu.push(temp+loc/2);
totalCount += 2;
}
}
loc /= 2;
}
for(int i=0;i<leaf.size();i++){
i<leaf.size()-1?cout<<leaf[i]<<" ":cout<<leaf[i];
}
return 0;
}