PAT 1064. Complete Binary Search Tree
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
分析
首先这是一个二叉搜索树,它的中序遍历结果时一个非递减的数列,并且又是个完全二叉树,就如果用数组去储存的话,已知父节点下标为s的话,左孩子的下标为2*s+1,右孩子的下标为2*s+2,并且输出的格式是层级输出,即一层一层的从左到右输出。这道题相当于已知中序遍历的结果(给的数组从小到大排序)了,让你输出层级输出的结果。
因为一旦完全二叉搜素树确定了,由于它的特定结构,它的层级输出的顺序也就确定了,关系是一一对应的,只需对0~n-1也中序遍历一遍,并和完全二叉树的中序遍历结果一一对应,再输出即可。
#include<iostream>
#include<algorithm>
using namespace std;
int a[1001],res[1001],tag=0;
void inorder_traversal(int s,int n){
if(2*s+1<n) pre(2*s+1,n);
res[s]=a[tag++];
if(2*s+2<n) pre(2*s+2,n);
}
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
inorder_traversal(0,n);
for(int i=0;i<n;i++)
i>0?cout<<" "<<res[i]:cout<<res[i];
return 0;
}