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
题意:
给出N个非负整数,要用它们构建一棵完全二叉排序树。输出这棵完全二叉排序树的层序遍历序列。
分析:
主要是掌握完全二叉树(CBT)和二叉查找树(BST)的性质。
完全二叉树:
除了最下面一层之外,其余层的结点个数均都达到了当层能达到的最大结点数,且最下面一层只从左到右连续存在若干结点,而这些连续结点右边的结点全部不存在。
- 给完全二叉树的所有结点从上到下,从左到右的顺序编号(编号从1开始)。
①对完全二叉树的任意一个结点(设编号为x),其左孩子的编号一定是2x,而右孩子的编号一定是2x+1。
②由性质①可知,可以用数组存储完全二叉树,下标即编号。
③判断某个结点为叶结点: 该结点(记下标为root)的左子结点的编号2*root大于结点总个数N。
④判断某个结点为空结点: 该结点下标root大于结点总个数N。
⑤该数组中元素存放的顺序恰好为该完全二叉树的层序遍历序列。
二叉查找树:
- 二叉查找树的中序遍历序列是有序的(从小到大)
那么由上述性质可知,该题应将输入进行排序(从小到大),然后利用中序遍历将数据逐个放入。
以下代码:
#include<cstdio>
#include<algorithm>
using namespace std;
int input[1100],tree[1100],index=0,N;
void creat(int root) //模拟中序遍历
{
if(root>N) //编号越界,说明该结点为空
return;
creat(2*root); //左子树
tree[root]=input[index++];
creat(2*root+1); //右子树
}
int main()
{
scanf("%d",&N);
for(int i=0;i<N;i++)
scanf("%d",&input[i]);
sort(input,input+N);
creat(1);
for(int i=1;i<=N;i++) //将数组顺序输出,即为层序序列
{
if(i!=1)
printf(" ");
printf("%d",tree[i]);
}
return 0;
}