原题干:
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
生词:
recursively:递归 properties:特性
distinct:明显的,不寻常的,有区别的
non-negative:非负
题目大意:给定一串序列,要求将这串序列构建成一棵完全二叉排序树,并给出层序遍历序列。
这道题给定的序列要构建完全二叉树。完全二叉树有这样的定义:设完全二叉树的任何节点的编号为X,则其左节点的编号一定是2X,右节点的编号一定是2X+1。
又想到完全二叉排序树的中序遍历是有序的序列,所以将给定的序列排序后,就会二叉树的中序遍历序列。
我们定义静态二叉树,采用中序遍历的方式给二叉树递归赋值,得到的二叉树按照1,2,3,4......的顺序就是二叉树的层序遍历顺序,所以可以直接遍历数组输出。
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int input[1010], tree[1010];
int index, cnt;
void inorder(int root){
if(root > cnt) return;
inorder(root*2);
tree[root] = input[index++];
inorder(root*2 + 1);
}
int main(){
cin >> cnt;
for(int i = 0 ; i < cnt ; i++)
cin >> input[i];
sort(input, input + cnt);
inorder(1);
for(int i = 1; i <= cnt; i++){
cout << tree[i];
if(i < cnt) cout << " ";
}
return 0;
}