A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
二叉搜索树(BST)被递归地定义为具有以下属性的二叉树:
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.
完全二进制树(CBT)是完全填充的树,除了最底层例外,左到右都被填充满。
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.
现在给定不同的非负整数键的序列,如果可以构造唯一的BST则需要树必须也是CBT。 您应该输出此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.
每个输入文件包含一个测试用例。 对于每种情况,第一行包含正整数N(≤1000)。 然后下一行给出N个不同的非负整数键。 一行中的所有数字由一个空格分隔,并且不大于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
10
1 2 3 4 5 6 7 8 9 0
Sample Output:
6 3 8 1 5 7 9 0 2 4
思路:
二叉搜索树中序遍历序列自然有序!顺序从小到大!
二叉搜索树的左节点<根节点<右结点,中序遍历的顺序为左->根->右,正好就是从小到大的顺序。
又因为是完全二叉搜索树,根节点为0时,节点i的左孩子和右孩子分别是2i和2i+1, 因此可以用数组实现。
首先要对输入的数据进行排序。STL中有函数sort,是可以直接对数组进行排序,复杂度为n*log2(n),默认为升序排列。用这个函数,需要的头文件如下:
#include <algorithm>
using namespace std;
sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址
但是,也可以自己写一个cmp函数,按照自己的意愿进行排序。比如下面这个sort,就是降序排序。
int cmp( const int &a, const int &b )
{
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);//对数组a降序排序
这道题的思路是:将输入的数据用sort函数从小到大排序->得到的序列是二叉搜索树的中序遍历序列->输出二叉搜索树的层次遍历序列。
#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;
}