题目
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.
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
题目大意
创建二叉搜索树,且该树同时为完全二叉树。
思路
创建BST一般方法是链表插入,但注意到是完全二叉树,其特殊性质是在数组中,若根节点下标为i,则2i为左子树根节点下标,2i+1为右子树根结点下标(两下标皆不超过节点数n),所以可以考虑使用数组进行创建比较简便。
显然BST的中序遍历是有序的,在构造完全二叉树的时候按中序构造即可(注意要先进行排序)。
代码实现
#include <stdio.h>
#include <stdlib.h>
#define maxSize 1001
int tree[maxSize]; // 存放完全二叉搜索树
int node[maxSize]; // 存放节点信息
int root, pos; // 树中根节点下标,存储节点下标
int n;
/*qsort比较函数*/
int cmp(const void *a, const void *b)
{
return *(int *)a - *(int *)b;
}
/*tree数组输出,即为层次遍历输出*/
void print(int a[], int n)
{
int flag = 0;
int i;
for (i = 1; i <= n; ++i)
{
if(!flag)
{
flag = 1;
printf("%d", a[i]);
}
else
printf(" %d", a[i]);
}
}
/*创建CBST*/
void build(int root)
{
if (root > n)
return;
int lchild = root * 2;
int rchild = root * 2 + 1;
/*关键步骤,中序遍历建树*/
build(lchild);
tree[root] = node[pos++]; // 按序将存储的结点插入树中
build(rchild);
}
int main(void)
{
int i;
scanf("%d", &n);
for(i = 1; i <= n; ++i)
scanf("%d", &node[i]);
qsort(&node[1], n, sizeof(int), cmp);
pos = 1;
build(1);
print(tree, n);
return 0;
}
参考