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 (≤). 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

题目分析:刚开始我想的是先把末尾的多余的元素 计入计算根节点的位置 但欠缺考虑到对于k层树来说
若第k层元素大于2的k-1次 我这样的做法就出了问题 只过了2个点(21分) //给分真高
 #define _CRT_SECURE_NO_WARNINGS
#include <climits>
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
int Array[];
int Queue[];
void EnQueue(int begin, int end,int pos) //左闭右开
{
if (begin >= end)
return;
Queue[pos] = Array[(begin + end) / ];
EnQueue(begin, (begin + end)/, * pos + );
EnQueue((begin + end) / + , end, * pos + );
}
int main()
{
int N;
cin >> N;
for (int i = ; i < N; i++)
cin >> Array[i];
sort(Array, Array + N);
int sum = ;
for (; sum * < N; sum *= );
int offset = (N - sum)/;
int i = ;
Queue[i] = Array[N / + offset]; //根节点入队
//分别递归处理左右
EnQueue(, N / + offset, * i + );
EnQueue(N / + offset + ,N, * i + );
for (int i = ; i < N - ; i++)
cout << Queue[i] << " ";
if(N!=)
cout << Queue[N- ];
return ;
}

参考别人的做法
 #define _CRT_SECURE_NO_WARNINGS
#include <climits>
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
int Array[];
int Queue[];
int N;
int id;
void EnQueue(int root) //左闭右开
{
if (root >= N)
return;
EnQueue( * root + );
Queue[root] = Array[id++];
EnQueue( * root + );
}
int main()
{
cin >> N;
for (int i = ; i < N; i++)
cin >> Array[i];
sort(Array, Array + N);
EnQueue();
for (int i = ; i < N - ; i++)
cout << Queue[i] << " ";
cout << Queue[N - ];
return ;
}

来自https://blog.csdn.net/feng_zhiyu/article/details/82219702

果然 很多代码真的是又短又好 虽然原理简单 但体现出的思想正是让我感到震撼

 
04-28 02:26