04-树6 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.
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
解题思路
如果只是构建一个二叉搜索树那么可以一个一个地插入,但现在是构建完全二叉搜索树,这个方法便不行了。联想到二叉搜索树中序遍历是递增的这一个特点,我们可以通过中序遍历来建树。因此我们需要先将输入的序列排序,然后通过排序后的序列来建树。由于题目要求层次遍历输出序列,用顺序结构保存树更简单。
代码
#include <stdio.h>
#define MAXSIZE 1000
//数组a存递增序列,数组b存层次遍历序列
int a[MAXSIZE], b[MAXSIZE];
void quickSort(int low, int high);
void inorder(int root, int n);
int main() {
int N;
scanf("%d", &N);
if (N) {
for (int i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
quickSort(0, N - 1);//让数组a递增
inorder(0, N);//中序遍历数组b,并为b赋值
printf("%d", b[0]);
for (int i = 1; i < N; i++) {
printf(" %d", b[i]);
}
}
return 0;
}
//对数组a快速排序
void quickSort(int low, int high) {
if (low >= high) return;
int tmp = a[low];
int i = low, j = high;
while (i < j) {
while (i < j && a[j] >= tmp) j--;
a[i] = a[j];
while (i < j && a[i] <= tmp) i++;
a[j] = a[i];
}
a[i] = tmp;
quickSort(low, i - 1);
quickSort(i + 1, high);
}
//对数组b中序遍历
int index = 0;
void inorder(int root, int n) {
if (root >= n) return;
int left = 2 * root + 1;
int right = left + 1;
inorder(left, n);
b[root] = a[index++];//由于a是递增的,因此可以利用a为b赋值
inorder(right, n);
}