1064 Complete Binary Search Tree (30 分)
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.
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.
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.
一,基本思想:
与普通的二叉排序树不同,完全二叉排序树必须保证是完全二叉树,不过完全二叉排序树表达起来也更简单,可以用数组来表示,即root表示根节点,2*root是左孩子,2*root+1是右孩子,把给出数据从小到大排序,按照中序遍历的顺序依次赋值即可,数组的键表示这是第几号结点,数组的值表示这个结点的值,把数组按顺序输出即为层序遍历的结果。
二,正确代码:
#include<cstdio> #include<algorithm> using namespace std; //到7:50 到8:25 const int max_n = 1100; int n = 0; int index = 0; int arr[max_n] = { 0 }; int CBT[max_n] = { 0 }; void inOrder(int root) { if (root > n)return; inOrder(2 * root); CBT[root] = arr[index++]; inOrder(2 * root + 1); } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } sort(arr, arr + n); inOrder(1); for (int i = 1; i <= n; i++) { printf("%d", CBT[i]); if (i != n) { printf(" "); } } return 0; }