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.
解答:
这道题和1043 Is It a Binary Search Tree(25 分)有异曲同工之妙,就是建树,然后输出。
只是,1043题题目给出的是BST或mBST的前序遍历,这样便很方便的进行建树;
而这道题,却给的是完全BST ,通过对测试用例进行模拟,便发现所有值的由小到大排序就是这棵树的中序遍历。由此我们可以利用完全二叉树的性质,即子节点序号 = 父节点序号*2 或 父节点序号 * 2 + 1,这样便可以用递归在数组中建树。
AC代码如下:
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
int tree[1010];
int index = 0;
vector<int> vec;
void inOrder(int pos, int n)
{
if(pos > n) return;
inOrder(pos * 2, n);
tree[pos] = vec[index++];
inOrder(pos * 2 + 1, n);
}
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i)
{
int d;
scanf("%d", &d);
vec.push_back(d);
}
sort(vec.begin(), vec.end());
inOrder(1, n);
for(int i = 1; i <= n; ++i)
{
printf("%d%c", tree[i], i == n ? '\n' : ' ');
}
return 0;
}